【问题标题】:Wordpress display parent category as heading with children underneathWordpress 将父类别显示为标题,下方有子项
【发布时间】:2021-03-12 11:26:54
【问题描述】:

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

  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
        
        } ?>

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

【问题讨论】:

    标签: wordpress loops foreach categories


    【解决方案1】:

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

    <?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);
    

    【讨论】:

    • 尽管我希望能够为孙辈添加更多标记,但不知道如何在这里进行。
    • @user144271 专门针对它们,您可以使用 CSS 子选择器,即ul &gt; li &gt; li,或者如果您特别需要类,那么您需要为此编写一些逻辑 - 可能最好发布一个新问题,如果您特别卡在某个方面:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多