关于php: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 "时才为真)类别为"库存"):

1
2
3
4
5
6
7
8
9
<?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()等于" in-stock "的数量来显示该类别的产品数量:

1
2
3
4
5
6
7
<?php
$terms = get_terms( 'product_cat' );
foreach( $terms as $term ){
    echo 'Product Category: ' . $term->name . ' - Count: ' . $term->count ."\
\
"
;}
?>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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!';
        }
    }
?>

我不知道它是否完全指向发问者提出的问题,但是我在WP REST API中的get_terms也有类似的问题。经过一个小时的调试,我发现WooCommerce仅在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请求:

1
2
3
4
5
6
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');


在if语句之前,使用测试代码检查类别中是否有现货,然后在if语句中添加其他条件。请参见下面的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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!';}
?>