Answers:
您正在寻找的功能是get_term_by
。您可以这样使用它:
<?php $term = get_term_by('slug', 'my-term-slug', 'category'); $name = $term->name; ?>
结果$term
是成为包含以下内容的对象:
term_id
name
slug
term_group
term_taxonomy_id
taxonomy
description
parent
count
该法典在解释此功能方面做得很好:http : //codex.wordpress.org/Function_Reference/get_term_by
当分类法不可用/未知时,这提供了一个答案。
就我而言,在使用get_term_by时,在某些情况下仅存在术语Slug(无术语ID或分类法)。导致我来到这里。但是,提供的答案并不能完全解决我的问题。
$taxonomy
// We want to find the ID to this slug.
$term_slug = 'foo-bar';
$taxonomies = get_taxonomies();
foreach ( $taxonomies as $tax_type_key => $taxonomy ) {
// If term object is returned, break out of loop. (Returns false if there's no object)
if ( $term_object = get_term_by( 'slug', $term_slug , $taxonomy ) ) {
break;
}
}
$term_id = $term_object->name;
echo 'The Term ID is: ' . $term_id . '<br>';
var_dump( $term_object );
The Term ID is: 32
object(WP_Term)
public 'term_id' => int 32
public 'name' => string 'Example Term'
public 'slug' => string 'example-term'
public 'term_group' => int 0
public 'term_taxonomy_id' => int 123
public 'taxonomy' => string 'category'
public 'description' => string ''
public 'parent' => int 0
public 'count' => int 23
public 'filter' => string 'raw'
如下所示,该概念获取的数组,在数组中$taxonomies
循环,然后IF get_term_by()
返回匹配项,然后立即退出foreach循环。
注意:我试图搜索一种方法来从术语Slug中获取相关的分类法(ID或Slug),但是不幸的是,我无法在WordPress中找到任何可用的方法。
谢谢,这对我有用。
我创建了一个函数,并根据需要反复使用它。
function helper_get_taxonomy__by_slug($term_slug){
$term_object = "";
$taxonomies = get_taxonomies();
foreach ($taxonomies as $tax_type_key => $taxonomy) {
// If term object is returned, break out of loop. (Returns false if there's no object);
if ($term_object = get_term_by('slug', $term_slug, $taxonomy)) {
break;
}else{
$term_object = "Warn! Helper taxonomy not found.";
}
}
return $term_object;
}