![](/img/trans.png)
[英]Display a Sold out greyed button if all variations are out of stock in WooCommerce
[英]Display sold out on WooCommerce variable product when all variations are out of stock
在 WooCommerce 我使用下面的 function 如果產品缺貨,它會在產品縮略圖上添加售罄文本:
add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_sold_out_loop_woocommerce' );
function bbloomer_display_sold_out_loop_woocommerce() {
global $product;
if ( ! $product->is_in_stock() ) {
echo '<span class="soldout">Sold Out</span>';
}
}
它適用於簡單的產品,但不適用於可變產品。
對於具有變體的可變產品,如果我將除 1 變體之外的所有變體設置為 0 庫存數量,我注意到已售罄消息仍然出現在縮略圖上。 從技術上講,這是不正確的,因為我們確實有一些庫存。
有誰知道如何更改下面的代碼來處理這個問題?
您可以創建自定義條件 function 來檢查變量產品的所有變體是否“缺貨”,如下所示:
function is_variable_product_out_of_stock( $product ) {
$children_count = 0; // initializing
$variation_ids = $product->get_visible_children();
// Loop through children variations of the parent variable product
foreach( $variation_ids as $variation_id ) {{
$variation = wc_get_product($_variation_id); // Get the product variation Object
if( ! $variation->is_in_stock() ) {
$children_count++; // count out of stock children
}
}
// Compare counts and return a boolean
return count($variation_ids) == $children_count ? true : false;
}
然后您將在下面重新訪問的鈎子 function 中使用它:
add_action( 'woocommerce_before_shop_loop_item_title', 'display_products_loop_out_of_stock' );
function display_products_loop_out_of_stock() {
global $product;
if ( ( ! $product->is_type('variable') && ! $product->is_in_stock() )
|| ( $product->is_type('variable') && is_variable_product_out_of_stock( $product ) ) ) {
echo '<span class="soldout">Sold Out</span>';
}
}
代碼進入活動子主題(或活動主題)的functions.php文件。 它應該有效。
我制作了 @LoicTheAztec 的 function 的更輕版本,一旦找到庫存變量,它將停止循環:
function is_variable_product_out_of_stock($product) {
$variation_ids = $product->get_visible_children();
foreach($variation_ids as $variation_id) {
$variation = wc_get_product($variation_id);
if ($variation->is_in_stock())
return false;
}
return true;
}
也沒有致命錯誤,因為他在 function 中犯了兩個嚴重的錯別字。
你可以像他一樣做一些自定義的事情:
add_action('woocommerce_before_shop_loop_item_title', 'display_products_loop_out_of_stock');
function display_products_loop_out_of_stock() {
global $product;
if ((!$product->is_type('variable') and !$product->is_in_stock()) or ($product->is_type('variable') and is_variable_product_out_of_stock($product)))
echo '<span class="soldout">Sold Out</span>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.