Reduce WooCommerce product stock from WP All Import XML

61 views Asked by At

In WooCommerce with WP All Import, I'm using the following code to reduce the product stock quantity, but I'm getting 0 stock quantity (so it doesn't work):

function reduce_stock_based_on_custom_field( $product_id, $xml, $update ) {
    // Get the value of custom field 'bmind_stock'
    $bmind_stock = get_post_meta( $product_id, 'bmind_stock', true );

    // Check if 'bmind_stock' is 0 and reduce stock accordingly
     if ( $bmind_stock === 0 ) {
        // Get current stock
        $current_stock = get_post_meta( $product_id, '_stock', true );

        // Calculate new stock after reduction (e.g., reducing by 1)
        $new_stock = ($current_stock) - 1;

        // Update product stock
        wc_maybe_reduce_stock_levels( $product_id, '_stock', $new_stock );
    }
}

add_action( 'pmxi_saved_post', 'reduce_stock_based_on_custom_field', 10, 3 );

For example: If the product stock quantity is 6 and if I have for bmind_stock custom field a value of 0, I need to set the product stock to 5, so to reduce it to 1.

0

There are 0 answers