簡體   English   中英

Woocommerce get_term() 計數和 get_terms() 計數不同

[英]Woocommerce get_term() count and get_terms() count different

我在 woocommerce 的帖子中使用 php,並希望根據庫存水平顯示/隱藏某個類別中的產品。 當前使用 get_term() 並且產品數量包括“缺貨”產品。 使用 get_terms() 和同一類別的產品計數僅計算“庫存”產品。 如何編寫 if else 條件語句以使用特定產品類別的 get_terms 計數?

這是我到目前為止的代碼(當此類別中的產品“缺貨”時,“if”為真。僅當此類別中的產品“有貨”時,“if”才為真):

<?php
$term = get_term(373, 'product_cat' );
$category = $term->name;
$theCount = $term->count;
if ( ( $category = 'Outlet Other' ) && ( $theCount > 0 ) ){
    echo '[product_category category="outlet-other" per_page="100" orderby="menu_order" order="asc"]';} 
else {
    echo 'There are currently no products in this category.  Please check back soon!';}
?>

這是我在頁面上用於測試目的的其他代碼,它使用等於“庫存”數量的 get_terms() 顯示該類別的產品數量:

<?php
$terms = get_terms( 'product_cat' );
foreach( $terms as $term ){
    echo 'Product Category: ' . $term->name . ' - Count: ' . $term->count . "\r\n";}
?>
<?php
$term = get_term(373, 'product_cat' );
$category = $term->name;
$termsother = get_terms( 'product_cat' );
    foreach( $termsother as $termsnew ) {
        if (($termsnew->count > 0) && ($termsnew->name == $category)) {
          echo '[product_category category="' . $termsnew->slug . '" per_page="100" orderby="menu_order" order="asc"]';
        }
        elseif (($termsnew->count == 0) && ($termsnew->name == $category)) {
          echo 'There are currently no products in this category. Please check back soon!';
        }
        else {
          //echo 'If and ElseIf are false!';
        }
    }
?>

在 if 語句之前,使用您的測試代碼檢查該類別中是否有庫存產品,並在您的 if 語句中添加附加條件。 請參閱下面的代碼。

<?php
$term = get_term(373, 'product_cat' );
$category = $term->name;
$theCount = $term->count;
$terms = get_terms( 'product_cat' );
$category_has_in_stock_items = false;
    foreach( $terms as $term ) {
    if ($term->count > 0) {
        category_has_in_stock_items = true;
        break;
    }
}
if (($category = 'Outlet Other') && ($theCount > 0) && $category_has_in_stock_items){
    echo '[product_category category="outlet-other" per_page="100" orderby="menu_order" order="asc"]';} 
else {
    echo 'There are currently no products in this category.  Please check back soon!';}
?>

我不知道它是否完全指的是提問者提出的問題,但我在 WP REST API 中的get_terms遇到了類似的問題。 調試一個小時后,我發現 WooCommerce 僅在is_admin() || is_ajax()時才更改術語計數 is_admin() || is_ajax() :

https://github.com/woocommerce/woocommerce/blob/51912c659db971dcc1bf4a9a31a33777904ec627/includes/wc-term-functions.php#L530-L533

解決方案:在你的get_terms函數調用之前添加一個__return_true過濾器來模擬 WP REST API 中的 AJAX 請求:

add_filter('wp_doing_ajax', '__return_true');
$terms = get_terms([
    // [...]
    'pad_counts' => 1 // This is necessery if you want to correct parent categories count, too
]);
remove_filter('wp_doing_ajax', '__return_true');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM