根据WooCommerce产品库存自动更新产品自定义字段

时间:2020-10-15 17:25:25

标签: wordpress woocommerce product advanced-custom-fields stock

我在产品上附加了一个ACF字段“ DeliverySpeed”,其值为“快”和“慢”

每当产品库存为零或更少(有待补货的产品)时,我想更新此字段以将其值更改为“慢”

到目前为止,我仍在学习PHP,但这是我要去的东西,但是我确定缺少了很多东西,我只是不知道该朝哪个方向前进:

基于acf update field documentation


function automatically_change_delivery( ) {

global $product;

$fieldkey = "DeliverySpeed";
$valueslow = "Slow";

if($product->get_stock_quantity()<0) { update_field( $field_key, $valueslow, $post_id );

 } }

在此先感谢您的关注和建议。

1 个答案:

答案 0 :(得分:3)

一旦订单减少了产品库存水平,以下代码将自动更新您的产品自定义字段。因此,当产品有库存时,自定义字段值将为“快速”,否则为“慢”。

代码:

add_action( 'woocommerce_payment_complete', 'update_product_custom_field_after_reduced_stock_levels', 20, 2 );
add_action( 'woocommerce_order_status_completed', 'update_product_custom_field_after_reduced_stock_levels', 20, 2 );
add_action( 'woocommerce_order_status_processing', 'update_product_custom_field_after_reduced_stock_levels', 20, 2 );
add_action( 'woocommerce_order_status_on-hold', 'update_product_custom_field_after_reduced_stock_levels', 20, 2 );
function update_product_custom_field_( $order_id, $order = '' ) {
    // Continue only when order has reduced product stock levels
    if ( wc_string_to_bool( get_post_meta( $order_id, '_order_stock_reduced', true ) ) )
        return $order_id; // Exit
    
    if( ! $order || ! is_a( $order, 'WC_Order') ) {
        $order = wc_get_order( $order_id ); // Get the WC_Order object if it's empty
    }
    
    $field_key = 'DeliverySpeed';
        
    // Loop through order items
    foreach ( $order->get_items() as $item ) {
        $product     = $cart_item['data'];
        $product_id  = $product->get_id();
        $stock_qty   = $product->get_stock_quantity();
        $field_value = get_field( $field_key, $product_id ); // Get ACF field value
        
        if ( $stock_qty <= 0 && $field_value === 'Fast' ) {
            update_field( $field_key, 'Slow', $product_id );
        }
        elseif ( $stock_qty > 0 && $field_value === 'Slow' ) {
            update_field( $field_key, 'Fast', $product_id );
        }
    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。