如何显示当前的帖子分类法和术语
这是来自 Codex 的修改后的代码(见下面的链接),它将显示当前帖子的所有分类法以及附加的术语:
<?php
// get taxonomies terms links
function custom_taxonomies_terms_links() {
global $post, $post_id;
// get post by post id
$post = &get_post($post->ID);
// get post type by post
$post_type = $post->post_type;
// get post type taxonomies
$taxonomies = get_object_taxonomies($post_type);
$out = "<ul>";
foreach ($taxonomies as $taxonomy) {
$out .= "<li>".$taxonomy.": ";
// get the terms related to post
$terms = get_the_terms( $post->ID, $taxonomy );
if ( !empty( $terms ) ) {
foreach ( $terms as $term )
$out .= '<a href="' .get_term_link($term->slug, $taxonomy) .'">'.$term->name.'</a> ';
}
$out .= "</li>";
}
$out .= "</ul>";
return $out;
} ?>
这是这样使用的:
<?php echo custom_taxonomies_terms_links();?>
演示输出
country
如果当前帖子具有分类法,则输出可能如下所示city
:
<ul>
<li> country:
<a href="http://example.com/country/denmark/">Denmark</a>
<a href="http://example.com/country/russia/">Russia</a>
</li>
<li> city:
<a href="http://example.com/city/copenhagen/">Copenhagen</a>
<a href="http://example.com/city/moscow/">Moscow</a>
</li>
</ul>
参考
Codex 中的原始代码示例:
http://codex.wordpress.org/Function_Reference/get_the_terms#Get_terms_for_all_custom_taxonomies
希望这会有所帮助-我相信您可以将其适应您的项目;-)
更新
但是,如果我只想显示其中的一部分而不是全部怎么办?另外,我想自己命名它们,而不是用下划线给出分类名称。知道如何实现吗?
这是实现这一目标的一项修改:
function custom_taxonomies_terms_links() {
global $post;
// some custom taxonomies:
$taxonomies = array(
"country"=>"My Countries: ",
"city"=>"My cities: "
);
$out = "<ul>";
foreach ($taxonomies as $tax => $taxname) {
$out .= "<li>";
$out .= $taxname;
// get the terms related to post
$terms = get_the_terms( $post->ID, $tax );
if ( !empty( $terms ) ) {
foreach ( $terms as $term )
$out .= '<a href="' .get_term_link($term->slug, $tax) .'">'.$term->name.'</a> ';
}
$out .= "</li>";
}
$out .= "</ul>";
return $out;
}