所以碰巧我正在做的一个项目需要这样的东西。我只是编写了一个查询来选择一个自定义类型的所有帖子,然后检查他们使用的分类法的实际术语是什么。
然后我用get_terms()
然后我只使用了这两个列表中的那些,将其打包到一个函数中,我就完成了。
但我需要的不仅仅是ID:我需要名称,所以我添加了一个名为$fields
所以我可以告诉函数返回什么。然后我想get_terms
接受许多参数,并且我的函数仅限于post类型使用的术语,因此我又添加了一个if
声明,现在开始:
功能:
/* get terms limited to post type
@ $taxonomies - (string|array) (required) The taxonomies to retrieve terms from.
@ $args - (string|array) all Possible Arguments of get_terms http://codex.wordpress.org/Function_Reference/get_terms
@ $post_type - (string|array) of post types to limit the terms to
@ $fields - (string) What to return (default all) accepts ID,name,all,get_terms.
if you want to use get_terms arguments then $fields must be set to \'get_terms\'
*/
function get_terms_by_post_type($taxonomies,$args,$post_type,$fields = \'all\'){
$args = array(
\'post_type\' => (array)$post_type,
\'posts_per_page\' => -1
);
$the_query = new WP_Query( $args );
$terms = array();
while ($the_query->have_posts()){
$the_query->the_post();
$curent_terms = wp_get_object_terms( $post->ID, $taxonomy);
foreach ($curent_terms as $t){
//avoid duplicates
if (!in_array($t,$terms)){
$terms[] = $c;
}
}
}
wp_reset_query();
//return array of term objects
if ($fields == "all")
return $terms;
//return array of term ID\'s
if ($fields == "ID"){
foreach ($terms as $t){
$re[] = $t->term_id;
}
return $re;
}
//return array of term names
if ($fields == "name"){
foreach ($terms as $t){
$re[] = $t->name;
}
return $re;
}
// get terms with get_terms arguments
if ($fields == "get_terms"){
$terms2 = get_terms( $taxonomies, $args );
foreach ($terms as $t){
if (in_array($t,$terms2)){
$re[] = $t;
}
}
return $re;
}
}
用法:如果您只需要术语id列表,则:
$terms = get_terms_by_post_type(\'tag\',\'\',\'snippet\',\'ID\');
如果您只需要术语名称列表,则:
$terms = get_terms_by_post_type(\'tag\',\'\',\'snippet\',\'name\');
如果只需要术语对象列表,则:
$terms = get_terms_by_post_type(\'tag\',\'\',\'snippet\');
如果需要使用get\\u术语的额外参数,如:orderby、order、hierarchical。。。
$args = array(\'orderby\' => \'count\', \'order\' => \'DESC\', \'hide_empty\' => 1);
$terms = get_terms_by_post_type(\'tag\',$args,\'snippet\',\'get_terms\');
享受吧!
更新时间:
要将术语计数固定到特定的职位类型更改,请执行以下操作:
foreach ($current_terms as $t){
//avoid duplicates
if (!in_array($t,$terms)){
$terms[] = $t;
}
}
收件人:
foreach ($current_terms as $t){
//avoid duplicates
if (!in_array($t,$terms)){
$t->count = 1;
$terms[] = $t;
}else{
$key = array_search($t, $terms);
$terms[$key]->count = $terms[$key]->count + 1;
}
}