微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Wordpress 将父类别显示为标题,下面有子项

如何解决Wordpress 将父类别显示为标题,下面有子项

我有一个祖父母类别,其中有这样的子孙:

  1. 祖父母猫
    • 儿童猫 01
      • 孙猫 01
      • 孙猫 02
      • 孙猫 03
    • 儿童猫 02
      • 孙猫 01
      • 孙猫 02
      • 孙猫 03

我想在主要的祖父母类别页面上循环浏览这些内容,并显示每个子标题,下面有孙链接

到目前为止,我有这个显示所有孩子和孙子,但没有区分两者......

        <?PHP

        $this_category = get_category($cat);

        $args = (array (
            'orderby'=> 'id','depth' => '1','show_count' => '0','child_of' => $this_category->cat_ID,'echo' => '0'
        )); 

        $categories = get_categories( $args );
        
        foreach ( $categories as $category ) { 

            echo $category->name
        
        } ?>

如果有孩子,我需要一个规则......

解决方法

通过检查类别是否有父类别来识别这一点相对简单

<?php

    $this_category = get_category($cat);

    $args = (array (
        'orderby'=> 'id','depth' => '1','show_count' => '0','child_of' => $this_category->cat_ID,'echo' => '0'
    )); 

    $categories = get_categories( $args );
    
    foreach ( $categories as $category ) { 
       if (!$category->parent) {
           echo 'Has no parent';
       }

       echo $category->name;
    
    } ?>

或者使用递归方法,具体取决于您的需要

<?php
$this_category = get_category($cat);

function category_tree(int $categoryId = 0) {
  $categories = get_categories([
    'parent' => $categoryId,'echo' => 0,'orderby' => 'id','show_count' => 0
  ]);

  if ($categories) {
    foreach ($categories as $category) { 
      echo '<ul>';
        echo '<li>';
          echo $category->name;
          
          category_tree($category->term_id);
    }
  }

  echo '</li></ul>';
}

category_tree($this_category->cat_ID);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。