Add backorders stock status to Woocommerce variable product dropdown

久未见 提交于 2020-01-24 11:15:48

问题


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:



来源:https://stackoverflow.com/questions/55603766/add-backorders-stock-status-to-woocommerce-variable-product-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!