在WordPress管理中显示类别的父子关系

时间:2015-07-29 作者:logrexton

如何在wordpress admin中显示父类别下的子类别?在帖子上,类别框的格式如下所示:

类别1

第1.1子类第2类

2 个回复
最合适的回答,由SO网友:Domain 整理而成

编辑:

在帖子页面上,类别已经以分层方式显示,但带有复选框。因此,我假设您必须以以下格式在管理面板的某个位置显示所有类别/子类别的列表。

第1类,第1.1子类,第1.2子类,第2类,演示由您决定,我刚才给出了获取必要数据的逻辑,即所有类别和子类别的列表。

    $arg1 = array(
        \'parent\'                   => 0,
        \'orderby\'                  => \'name\',
        \'hide_empty\'               => 0,
        \'pad_counts\'               => false 
        );

    $categories = get_terms(\'category\', $arg1);  //or use your custom taxonomy name

    if( !empty($categories) && is_array($categories) ){

      echo \'<ul>\'; 

      foreach($categories as $cat){

        echo \'<li>\'.$cat->name;

        $arg2 = array(
                        \'child_of\'                 => $cat->term_id,
                        \'orderby\'                  => \'name\',
                        \'hide_empty\'               => 0,
                        \'pad_counts\'               => false 
                    );

        $sub_categories = get_terms(\'category\', $arg2); //or use your custom taxonomy name

        if(!empty($sub_categories) && is_array($sub_categories)){

          echo \'<ul>\';       

          foreach($sub_categories as $scat){

              echo \'<li>\'.$scat->name.\'</li>\';
          }
      echo \'</ul>\';
      }
      echo \'</li>\';
      }
    echo \'</ul>\';
    }

SO网友:prempal sharma

use this code for solving your problem.

<?php 
 $args = array( \'orderby\' =>\'name\',
                \'texonomy\' =>\'category\',
                \'child_of\' =>0,
                \'parent\' =>0 );

        $cats = get_categories($args);
        foreach ($cats as $cat) {
             echo $cat->name;
 $arg = array(\'orderby\' => \'name\',
             \'child_of\' =>0,
              \'parent\' =>$cat->term_id);
            $sub_cats =get_categories($arg);

                foreach ($sub_cats as $sub) {
                    echo \'<hr><br>\';
                    echo \'<h3>\'.$sub->name.\'</h3>\';
                    echo \'<hr><br>\';
                    $args = array(
                            \'post_type\' => \'post\',
                            \'tax_query\' => array(
                                array(
                                    \'taxonomy\' => \'category\',
                                    \'terms\'    => $sub->term_id,
                                ),
                            ),
                        );

                    $query = new WP_query( $args);
                    //echo "<pre>"; print_r($query); echo "</pre>";
                    while($query->have_posts()) : $query->the_post();
                    echo "<br>";
                    the_title();
                    echo "<br>";
                    the_content();
                    endwhile;
                echo "<hr>";
                }
        }
 ?>
结束