繁体   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