即使在 Wordpress 中没有 post 时如何显示类别名称
How to show a category name even when there is no post in Wordpress
我试图在我的分类法页面中显示 WordPress 类别名称,但每次该类别没有 post 时,它的名称将不会显示。我怎样才能显示它,即使它是空的?
<?php
$term = get_queried_object();
$term->slug;
$terms = get_the_terms($post->ID, 'productcat');
$nameTerm = $terms[0]->name;
$linkTerm = get_term_link($terms[0]);
?>
<span><?php echo $nameTerm ?></span>
听起来您想获取该类别的所有条款,而不仅仅是 post 条款。使用 get_terms
。您可以通过 hide_empty
来显示没有 post 的类别。
<?php
$term = get_queried_object();
$term->slug;
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
$nameTerm = $terms[0]->name;
$linkTerm = get_term_link($terms[0]);
?>
<span><?php echo $nameTerm ?></span>
// Prior to WordPress 4.5.0
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
// Since WordPress 4.5.0
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
) );
在这种情况下,您可以查看此代码
$taxonomy_text = "";
$cat_list = get_the_term_list( $post->ID, 'product_cat', '<strong>In this post:</strong> ', ', ', '' );
if ( '' != $cat_list ) {
$taxonomy_text .= "$cat_list<br />\n";
}
我试图在我的分类法页面中显示 WordPress 类别名称,但每次该类别没有 post 时,它的名称将不会显示。我怎样才能显示它,即使它是空的?
<?php
$term = get_queried_object();
$term->slug;
$terms = get_the_terms($post->ID, 'productcat');
$nameTerm = $terms[0]->name;
$linkTerm = get_term_link($terms[0]);
?>
<span><?php echo $nameTerm ?></span>
听起来您想获取该类别的所有条款,而不仅仅是 post 条款。使用 get_terms
。您可以通过 hide_empty
来显示没有 post 的类别。
<?php
$term = get_queried_object();
$term->slug;
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
$nameTerm = $terms[0]->name;
$linkTerm = get_term_link($terms[0]);
?>
<span><?php echo $nameTerm ?></span>
// Prior to WordPress 4.5.0
$terms = get_terms( 'product_cat', array(
'hide_empty' => false,
) );
// Since WordPress 4.5.0
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
) );
在这种情况下,您可以查看此代码
$taxonomy_text = "";
$cat_list = get_the_term_list( $post->ID, 'product_cat', '<strong>In this post:</strong> ', ', ', '' );
if ( '' != $cat_list ) {
$taxonomy_text .= "$cat_list<br />\n";
}