首页 文章

仅列出特定父类别中的帖子所在的子类别

提问于
浏览
0

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

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

  • Brand

  • 子类别1

  • 子类别2

  • Region

  • 子类别1

  • 子类别2

  • Grape

  • 子类别1

  • 子类别2

父类别永远不会改变,每个帖子在每个父母下面都会选择至少1个子类别,所以在LOOP中我只能按姓名列出父母 . 但我需要动态输出子类别,如下所示:

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

有这样简单的方法吗?看来这应该是Wordpress的基本功能?我查看了函数'get_categories'和'in_category',但它们似乎无法做到这一点 .

3 回答

  • 0

    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;
    
  • 0

    您可以使用 array_map ,这样您只能返回所需的类别 . 例如:

    array_map( function( $cat ) {
            if ( $cat->parent != 0 ) {
                return $cat;
            }
         },
         get_the_category()
    );
    
  • 0
    <?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; }
    } ?>
    

    试试这个

相关问题