简体   繁体   English

WordPress get_terms() 函数不显示 woocommerce 的自定义分类类别

[英]WordPress get_terms() function not display custom taxonomy categories for woocommerce

The following code I wrote is supposed to show all the product categories of a wordpress ecommerce website.我编写的以下代码应该显示 wordpress 电子商务网站的所有产品类别。

<?php $categories = get_terms( 
  array(
   'taxonomy' => 'product_cat',
   'hide_empty' => 'false',
   'numberposts' => -1)
  );
?>
<?php var_dump($categories); ?>
<?php foreach( $categories as $category ): ?>
 <h4 class="shop-category-name d-inline"><?php echo $category->name; ?></h4>
<?php endforeach; ?>

I'm using it inside a woocommerce hook that is responsible to render the contents before the main shop page, the woocommerce_before_main_content .我在 woocommerce 挂钩中使用它,该挂钩负责在主商店页面woocommerce_before_main_content之前呈现内容。 I'm not able to get the categories, I will see only one category and the others are not listed.我无法获得类别,我只会看到一个类别,其他类别未列出。 I'm not sure about, but maybe this can be something related to the fact that I'm using the function inside a woocommerce hook?我不确定,但也许这可能与我在 woocommerce 挂钩中使用该函数的事实有关? I had a similar issue with the shop page featured image, I was not able to display it because of this motivation and I have modified the code to use the wc_get_page_ID('pag name') .我在商店页面的特色图片上遇到了类似的问题,由于这个动机,我无法显示它,并且我修改了代码以使用wc_get_page_ID('pag name')

Is there a fix ?有解决办法吗?

Try to use it like this in the function, you used for woocommerce hook woocommerce_before_main_content尝试在函数中像这样使用它,您用于woocommerce hook woocommerce_before_main_content

add_action( 'woocommerce_before_main_content', 'woo_cats', 20, 0 );
function woo_cats(){
 $cat_args = array(
    'orderby'    => 'name',
    'order'      => 'asc',
    'hide_empty' => false,
);

$product_categories = get_terms( 'product_cat', $cat_args );

 if( !empty($product_categories) ){
    echo '<ul>';
    foreach ($product_categories as $key => $category) {
        echo '<li>';
        echo '<a href="'.get_term_link($category).'" >';
        echo $category->name;
        echo '</a>';
        echo '</li>';
    }
    echo '</ul>';
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM