如何检索附加到帖子和其他帖子类型的所有WordPress术语?假设我不知道/不关心分类法、术语名称/术语id等,我只知道post\\u id。谢谢。
如何将WordPress术语附加到帖子上?
3 个回复
SO网友:EAMann
有一个专门用于此的函数,叫做wp_get_post_terms()
.
不幸的是,您确实需要关心分类法。如果未指定分类法,它将返回所有“post\\u标记”术语:
$terms = wp_get_post_terms( $post_id, $taxonomy, $args )
$post_id
是您正在处理的帖子的ID(默认为0)$taxonomy
要为其检索术语的分类的名称(默认为“post\\u tags$args
是其他默认参数的替代数组(请参见Codex 有关详细信息)
SO网友:Ryan Meier
嗯。你可以尝试获取所有分类法,以及与帖子ID和分类法相关的所有术语。
$taxonomies = get_taxonomies( \'\', \'names\' );
$terms = wp_get_object_terms($post->ID, $taxonomies);
我还没有机会亲自尝试一下。SO网友:Mattvic
要获取附加到帖子的所有分类的所有术语,可以使用以下功能:
function my_post_terms() {
// Get an array of all taxonomies for this post
$taxonomies = get_taxonomies( \'\', \'names\' );
// Are there any taxonomies to get terms from?
if ( $taxonomies ) {
// Call the wp_get_post_terms function to retrieve all terms. It accepts an array of taxonomies as argument.
$arr_terms = wp_get_post_terms( get_the_ID(), array_values( $taxonomies ) , array( "fields" => "names" ) );
// Convert the terms array to a string
$terms = implode( \' \',$arr_terms );
// Get out of here
return $terms;
}
}
现在,您可以在模板中使用它:<?php echo my_post_terms(); ?>
如果需要所有术语或链接的HTML列表,只需循环使用$arr\\u terms数组即可。结束