Woocommerce get_term()count和get_terms()计数不同

时间:2015-04-21 14:05:05

标签: php wordpress woocommerce

我在一个帖子上使用php进行woocommerce,并希望根据他们的库存水平显示/隐藏某个类别的产品。目前使用get_term()和产品计数包括"缺货"产品。使用get_terms()和同一类别的产品计数仅计入"库存"产品。如何编写if else条件语句以使用特定产品类别的get_terms计数?

这是我到目前为止的代码("如果"属于此类别中的产品是"缺货"。想要"如果" ;只有当此类别的产品是"库存")时才是真实的:

<?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()等于&#34;库存&#34;来显示此类别的产品计数。量:

<?php
$terms = get_terms( 'product_cat' );
foreach( $terms as $term ){
    echo 'Product Category: ' . $term->name . ' - Count: ' . $term->count . "\r\n";}
?>

3 个答案:

答案 0 :(得分:1)

<?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!';
        }
    }
?>

答案 1 :(得分:0)

在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!';}
?>

答案 2 :(得分:0)

我不知道它是否完全指向发问者提出的问题,但是我在WP REST API中遇到get_terms时遇到了类似的问题。经过一个小时的调试,我发现WooCommerce仅在is_admin() || is_ajax()时才更改条款计数:

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

解决方案:在__return_true函数调用之前添加get_terms过滤器,以在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');