列出所有分类术语/显示链接(如果附加了帖子),否则显示名称

时间:2014-11-08 作者:Schakelen

我正在寻找一种方法来列出自定义分类法中的所有术语。只有附有帖子的条款才应该有指向存档页面的链接。如果没有贴子,则只应显示姓名。

有什么想法吗?谢谢

<?php
$taxonomy = \'cat\';
$queried_term = get_term_by( \'slug\', get_query_var($taxonomy) );
$terms = get_terms($taxonomy);
if ( $terms !== 0 ) {
    foreach ( $terms as $term ) {
        echo $term->name . ", ";
    }
}
if ( $terms > 0 ) {
    foreach ( $terms as $term ) {
        echo \'<li><a href="\' . $term->slug . \'">\' . $term->name .\'</a></li>\';
    }
}
?>

3 个回复
SO网友:SLH

我不太明白你的问题,但试试这个。注释中有解释。

// your taxonomy name
$tax = \'post_tag\';

// get the terms of taxonomy
$terms = get_terms( $tax, [
  \'hide_empty\' => false, // do not hide empty terms
]);

// loop through all terms
foreach( $terms as $term ) {

  // if no entries attached to the term
  if( 0 == $term->count )
    // display only the term name
    echo \'<h4>\' . $term->name . \'</h4>\';

  // if term has more than 0 entries
  elseif( $term->count > 0 )
    // display link to the term archive
    echo \'<h4><a href="\'. get_term_link( $term ) .\'">\'. $term->name .\'</a></h4>\';

}
希望对你有帮助。

SO网友:Schakelen

谢谢你的帮助!我做了一些小的调整,现在可以正常工作了:

<?php
// your taxonomy name
$tax = \'cat\';

// get the terms of taxonomy
$terms = get_terms( $tax, $args = array(
  \'hide_empty\' => false, // do not hide empty terms
));

// loop through all terms
foreach( $terms as $term ) {

    // Get the term link
    $term_link = get_term_link( $term );

    if( $term->count > 0 )
        // display link to term archive
        echo \'<a href="\' . esc_url( $term_link ) . \'">\' . $term->name .\'</a>\';

    elseif( $term->count !== 0 )
        // display name
        echo \'\' . $term->name .\'\';
}
?>
这太棒了!

SO网友:Everaldo Matias

只是对Schakelen的评论进行了改进,以测试是否有东西返回

// your taxonomy name
$tax = \'cat\';

// get the terms of taxonomy
$terms = get_terms( $tax, $args = array( 
\'hide_empty\' => false, // do not hide empty terms
));

    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){                

        // loop through all terms
        foreach( $terms as $term ) {

            // Get the term link
            $term_link = get_term_link( $term );

            if( $term->count > 0 )
                // display link to term archive
                echo \'<a href="\' . esc_url( $term_link ) . \'">\' . $term->name .\'</a>\';

            elseif( $term->count !== 0 )
                // display name
                echo \'\' . $term->name .\'\';
        }
    }

结束

相关推荐

Display taxonomy term slugs

我希望在循环中显示当前帖子的分类术语的slug列表。<?php $terms = get_the_terms( $post->ID, \'wpsc_product_category\' ); if ( !empty( $terms ) ){ $term = array_shift( $terms ); echo $term->slug; } ?> 我目前使用的函数可以工作,尽管它只显示第一个分类术语的slug,而不是全部。e、 g.一个岗位分配给多个岗位wpsc_prod