0

要么这比它需要的要难,要么我只是不太了解 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”,但它们似乎无法做到这一点。

4

3 回答 3

0

发布到 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;
于 2013-10-21T20:46:01.943 回答
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; }
} ?>

尝试这个

于 2013-10-20T16:52:13.770 回答
0

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

array_map( function( $cat ) {
        if ( $cat->parent != 0 ) {
            return $cat;
        }
     },
     get_the_category()
);
于 2018-10-30T12:06:43.187 回答