questions

Display custom stock status based on stock quantity in admin products list table

Rate this post

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?

 

✔️Solution:

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

 

Leave a Reply

Your email address will not be published.

Back to top button