我有一些帖子,只有当它们是给定父类别的子类别时,我才想在帖子内容后回显这些类别。
示例:
父类别:目标;目标:品牌意识、品牌参与度
如果一篇文章被分类,我希望它呼应出这些类别:
<?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);
}
?>
最合适的回答,由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。