仅当类别是给定类别的子级时才回显类别

时间:2012-08-14 作者:Keefer

我有一些帖子,只有当它们是给定父类别的子类别时,我才想在帖子内容后回显这些类别。

示例:

父类别:目标;目标:品牌意识、品牌参与度

如果一篇文章被分类,我希望它呼应出这些类别:

<?php
    $categories = get_the_category();
    $seperator = \' \';
    $output = \'\';
    if($categories)
    {
        foreach($categories as $category) 
        {
            $output .= \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a>\'.$seperator;
        }
        echo trim($output, $seperator);
    }
?>
我正在使用它,但它显然输出所有类别,而不仅仅是;“目标”;鼻涕虫

编辑:当前设置看起来像这样,但似乎不起作用。如果我用身份证,没关系:

<?php
        $categories = get_the_category();
        $seperator = \', \';
        $output = \'<strong>GOAL:</strong> \';
        $category = get_category_by_slug(\'goal\');
        if($categories)
        {
            foreach( $categories as $category ) 
            {
            if ( $category->parent == $category->term_id )
                $output .= \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a>\'.$seperator;
        }
        echo trim($output, $seperator);
}
?>

4 个回复
最合适的回答,由SO网友:Jasper Denkers 整理而成

更改:

$goal = get_category_by_slug(\'goal\');
foreach($categories as $category) 
{
    $output .= \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a>\'.$seperator;
}
进入:

foreach( $categories as $category ) {
    if ( $category->parent == $goal->term_id)
        $output .= \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a>\'.$seperator;
}
更换位置\'123\' 具有目标类别的ID。

SO网友:eddiemoya

我同意上述答案,只是它应该使用get_category_by_slug() 而不是硬编码的ID。这些评论让人有点困惑,因为问题也被更改了-所以我把它分成了我自己的答案。

要将此转换为上面的逻辑位。。。

<?php
    $goal_id = get_category_by_slug(\'goal\');

    $categories = get_the_category();
    $seperator = \' \';
    $output = \'\';
    if($categories)
    {
        foreach($categories as $category) 
        {
            if($category->parent == $goal->term_id){
                $output .= \'<a href="\'.get_category_link($category->term_id ).\'" title="\' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . \'">\'.$category->cat_name.\'</a>\'.$seperator;
            }
        }
        echo trim($output, $seperator);
    }
?>
我假设slug 您的“目标”类别goal.

SO网友:amit

使用条件检查怎么样?

下面的示例检查ID为(4)的父类别。

示例-

//To show child  of cat with id - 4
if($category->category_parent == \'4\') 
    $output .= \'foo\';

SO网友:Jonathan DS

您可以使用get\\u the\\u category\\u list(“”,$category\\u id,$optional\\u post-id)

http://codex.wordpress.org/Function_Reference/get_the_category_list

结束