从类别名称生成的父类别和子类别默认文本

时间:2019-12-18 09:57:38

标签: wordpress taxonomy-terms wp-list-categories

在我无法在网站上执行的操作上,我需要帮助。

我的页面上有几个类别和子类别。对于例如

  • 食物
    • 苹果
    • 橙色
  • 衬衫
  • 笔记本电脑
    • HP
    • 戴尔

我希望在每个主类别页面和子类别页面上都显示一个默认文本,

对于子类别

The best Food Apple you can get.

对于主要类别

The best Food you can get

我暂时使用以下代码,但主要类别仍显示子类别,例如FoodApple。理想情况下,主要类别应仅显示您可以获得的最佳食物。

<h2 class="supply">The best 

   <?php
$terms = get_the_terms( get_the_ID(), 'product_cat' );

foreach ( $terms as $term ){
    if ( $term->parent == 0 ) {
        echo $term->name ;
    }
}

foreach ( $terms as $term ){
    if ( $term->parent == !0 ) {
        echo $term->name ;
    }
}
?>  you can get </h2>

如果有人可以帮助我,我将非常感激。

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您的第二个条件对于儿童而言是不正确的。 替换

foreach ( $terms as $term ){
if ( $term->parent == !0 ) {
    echo $term->name ;
}

}

使用

foreach ( $terms as $term ){
if ( !$term->parent == 0 ) {
    echo $term->name ;
}

}

检查是否正常