Support

Account

Home Forums General Issues Auto update product custom field based on stock

Helping

Auto update product custom field based on stock

  • I have an ACF field “DeliverySpeed” attached to Products with the values ‘Fast’ and ‘Slow’

    I am trying to update this field to change to value ‘Slow’ automatically every time the product stock is zero or less (product on backorder)

    I have managed to come up to this code so far however it is not doing it and I can’t find out what seems to be wrong:

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

    Thank you in advance for the attention and advice.

  • Anyone? 🙁
    I can’t figure out why this code is not updating the field

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.