Jaime Matos
Jaime Matos

Reputation: 343

Auto update product custom field based on WooCommerce product stock

I have an ACF field "DeliverySpeed" attached to Products with the values 'Fast' and 'Slow'

I would like to update this field to change to value 'Slow' every time the product stock is zero or less (product on backorder)

I am still learning PHP so far this is what I got to but I am sure different things are missing, I just don't know in which direction to go:

based on 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 );

 } }

Thank you in advance for the attention and advice.

Upvotes: 2

Views: 964

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253804

The following code will update automatically your product custom field once order has reduced product stock levels. So when product has stock the custom field value will be 'Fast' otherwise 'Slow'.

The code:

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 );
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Upvotes: 3

Related Questions