【问题标题】:List only child categories a post is in, of a specific parent category仅列出特定父类别的帖子所在的子类别
【发布时间】:2013-10-20 16:13:22
【问题描述】:

要么这比它需要的要难,要么我只是不太了解 WordPress/PHP :( 我想要做的就是显示特定父类别的子类别/子类别......但前提是帖子属于那些子类。具体例子:

我正在建立一个葡萄酒评论网站,这些是类别:

  • 品牌
    • 子类别 1
    • 子类别 2
  • 地区
    • 子类别 1
    • 子类别 2
  • 葡萄
    • 子类别 1
    • 子类别 2

父类别永远不会改变,每个帖子都会在每个父类别下至少选择一个子类别,因此在循环中我可以按名称列出父类别。但我需要动态输出子类别,如下所示:

Brand: <?php list_post_subcategories('brand'); ?>
Region: <?php list_post_subcategories('region'); ?>
Grape: <?php list_post_subcategories('grape'); ?>

有没有这样简单的方法?看起来这应该是Wordpress中的一个基本功能?我查看了函数 'get_categories' 和 'in_category' 但他们似乎无法做到这一点。

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:
    <?php $post_child_cat = array();
    foreach((get_the_category()) as $cats) {
        $args = array( 'child_of' => $cats->cat_ID );
        $categories = get_categories( $args );
        if( $categories ) foreach( $categories as $category ) {
        echo $category->cat_name; }
    } ?>
    

    试试这个

    【讨论】:

    • 谢谢,但这只是输出帖子的所有子类别。它并不特定于每个父类别。
    • 如果你只想要一个特定类别的孩子,你可以像$args = array( 'child_of' =&gt;''category name or id here );然后$categories = get_categories( $args );现在打印$categories
    • 嗯……像这样?可能不是,我试了一下,没有输出:&lt;?php $post_child_cat = array(); foreach((get_the_category()) as $cats) { $args = array( 'child_of' =&gt; 'brand' ); $categories = get_categories( $args ); if( $categories ) foreach( $categories as $category ) { echo $categories; } } ?&gt;
    【解决方案2】:

    posted to Wordpress Answers 获得更多帮助,@Milo 提供了一个很棒的代码解决方案:

    // get top level terms
    $parents = get_terms( 'category', array( 'parent' => 0 ) );
    // get post categories
    $categories = get_the_terms( $post->ID, 'category' );
    // output top level cats and their children
    foreach( $parents as $parent ):
    // output parent name and link
    echo '<a href="' . get_term_link( $parent ) . '">' . $parent->name . '</a>: ';
    // initialize array to hold child links
    $links = array();
    foreach( $categories as $category ):
        if( $parent->term_id == $category->parent ):
            // put link in array
            $links[] = '<a href="' . get_term_link( $category ) . '">' . $category->name .      '</a>';
        endif;
    endforeach;
    // join and output links with separator
    echo join( ', ', $links );
    endforeach;
    

    【讨论】:

      【解决方案3】:

      您可以使用array_map,这样您就可以只返回您想要的类别。例如:

      array_map( function( $cat ) {
              if ( $cat->parent != 0 ) {
                  return $cat;
              }
           },
           get_the_category()
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多