-->

Add backorders stock status to Woocommerce variabl

2019-07-03 23:16发布

问题:

I would like to show the stock status of variable products in the dropdown menu, including 'on backorder' as most products on my site are available on backorder rather than being 'out of stock'.

I have tried the answer from How to add variation stock status to Woocommerce product variation dropdown however, every variable is listed as 'in stock' because the product is set to allow backorders.

I would like to incorporate checking the actual stock levels like below, but I can't get it to work properly with the above link.

$var_stock_count = $variation->get_stock_quantity();

// if there are 0 or less, display 'on backorder'
if( $var_stock_count <= 0 ) {
   return ' - (On Backorder)';
}
else {
   return ' - (In Stock)';
}

I need help incorporating the two pieces of code together. Thank you!

回答1:

This updated function that will handle products on backorders (when stock quantity is less than 1):

// Function that will check the stock status and display the corresponding additional text
function get_stock_status_text( $product, $name, $term_slug ){
    foreach ( $product->get_available_variations() as $variation ){
        if($variation['attributes'][$name] == $term_slug ) {
            $is_in_stock = $variation['is_in_stock'];
            $backordered = get_post_meta( $variation['variation_id'], '_backorders', true );
            $stock_qty   = get_post_meta( $variation['variation_id'], '_stock', true );
            break;
        }
    }
    $stock_status_text = $is_in_stock == 1 ? ' - (In Stock)' : ' - (Out of Stock)';
    return $backordered !== 'no' && $stock_qty <= 0 ? ' - (On Backorder)' : $stock_status_text;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Replaces the first function on this answer thread:

You will get something like: