列出当前分类中的子分类

时间:2015-07-22 作者:Jérémie Le Scoëzec

我有一个自定义分类法叫做book 用术语“科幻”、“浪漫”、“历史”等术语,这些分类都有4个子分类,我需要将其显示为子导航。

我想首先检索页面的当前分类,然后显示这些子分类的列表。

现在我有这个:

<?php
    $taxonomy     = \'book\';
    $orderby      = \'name\';
    $show_count   = 0;      // 1 for yes, 0 for no
    $pad_counts   = 0;      // 1 for yes, 0 for no
    $hierarchical = 1;      // 1 for yes, 0 for no
    $title        = \'\';
    $empty        = 0;

    $args = array(
        \'taxonomy\'     => $taxonomy,
        \'orderby\'      => $orderby,
        \'show_count\'   => $show_count,
        \'pad_counts\'   => $pad_counts,
        \'hierarchical\' => $hierarchical,
        \'title_li\'     => $title,
        \'hide_empty\'   => $empty
    );
?>

<ul class="guide-navigation">
    <?php wp_list_categories( $args ); ?>
</ul>
我需要获取页面的当前分类法,将其插入到代码中以列出其子分类法。我该怎么做?

1 个回复
SO网友:Rares P.

这可能会帮助您:

<?php

//first get the current term
$current_term = get_term_by( \'slug\', get_query_var( \'term\' ), get_query_var( \'taxonomy\' ) );

//then set the args for wp_list_categories
 $args = array(
    \'child_of\' => $current_term->term_id,
    \'taxonomy\' => $current_term->taxonomy,
    \'hide_empty\' => 0,
    \'hierarchical\' => true,
    \'depth\'  => 1,
    \'title_li\' => \'\'
    );
 wp_list_categories( $args );
?>
来源-https://codex.wordpress.org/Function_Reference/get_term_by (您可以硬编码“books”分类法,也可以只获取活动分类法)。

EDITED

您可以创建一个自定义函数来获取分类法的子项,就像下面的链接一样。

$hierarchy = get_taxonomy_hierarchy( \'book\' ); 

/**
 * Recursively get taxonomy hierarchy
 * 
 * @param string $taxonomy
 * @param int $parent - parent term id 
 * @return array
 */
function get_taxonomy_hierarchy( $taxonomy, $parent = 0 ) {
  // only 1 taxonomy
  $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;

  // get all direct decendents of the $parent
  $terms = get_terms( $taxonomy, array( \'parent\' => $parent ) );

  // prepare a new array.  these are the children of $parent
  // we\'ll ultimately copy all the $terms into this new array, but only after they
  // find their own children
  $children = array();

  // go through all the direct decendents of $parent, and gather their children
  foreach ( $terms as $term ){
    // recurse to get the direct decendents of "this" term
    $term->children = get_taxonomy_hierarchy( $taxonomy, $term->term_id );

    // add the term to our new array
    $children[ $term->term_id ] = $term;
  }

  // send the results back to the caller
  return $children;
}

http://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/

结束

相关推荐

中的字符串偏移量‘Taxonomy’非法

我有点纠结于以下错误Illegal string offset \'taxonomy\' in ... on line 175 Trying to get property of non-object in ... on line 177 Trying to get property of non-object in ... on line 178 我使用的代码是:function tax_cat_active( $output, $args ) { if