1
votes

I have added a custom stock status "Available Soon" for WooCommerce products. I want to change this status when the product stock quantity equals to 1.

I tried with a hook on the thank you page and it updated the status in database using query

update_post_meta( $product_id, '_stock_status', 'availablesoon' );

but when I see in WooCommmerce product dashboard there is still "In Stock" status for that specific product.

My full code:

add_action( 'woocommerce_thankyou', 'change_stock_status_cstm', 10, 1);
function change_stock_status_cstm( $order_id ){
$order = wc_get_order( $order_id );
$items = $order->get_items(); 
foreach ( $items as $item_id => $item ) {
    $product   = $item->get_product();
    $product_id = $item->get_variation_id() ? $item->get_variation_id() : 
    $item->get_product_id();
    if ( $product->get_stock_quantity() == 1 ) {
        update_post_meta( $product_id, '_stock_status', 'availablesoon' );
    }
}
}

Can anyone please tell me how to update stock status in dashboard as well?

2
Please show us what you tried so far!Bhautik
Added!! please checkchanchal bansal
No, it still not updated the status in product dashboard..chanchal bansal

2 Answers

2
votes

If you like to display the custom stock status on the admin products list table, based on the current stock quantity, you can just use:

// Admin stock html
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
    if ( $product->get_stock_quantity() == 1 ) {
        $stock_html = '<mark class="my-class" style="background:transparent none;color:#33ccff;font-weight:700;line-height:1;">' . __( 'Available soon', 'woocommerce' ) . '</mark>'; 
    }

    return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );

Related: How to add custom stock status to products in WooCommerce 4+

0
votes

you can try this.

$product = wc_get_product( $variant_post_id );  
wc_update_product_stock( $product,  $qty_new , 'set' );
wc_delete_product_transients( $variant_post_id );