Codex tools: Log in
Contents |
Get all Term data from database by Term field and data.
Warning: $value is not HTML-escaped for the 'name' $field. You must do it yourself, if required.
The default $field is 'id', therefore it is possible to also use null for field, but not recommended that you do so.
If $value does not exist, the return value will be false. If $taxonomy exists and $field and $value combinations exist, the Term will be returned.
<?php get_term_by( $field, $value, $taxonomy, $output, $filter ) ?>
The fields returned are:
Taxonomy_name is the name of taxonomy, not the term_name and is required; the id (term_id) is the ID of the term, not post_id;...
Remember:
↓ Taxonomy type (e.g. post_tag)
Terms in this taxonomy:
→ news
→ webdev
→ ...
Examples to get terms by name and taxonomy type (taxonomy_name as category, post_tag or custom taxonomy).
// Get term by name ''news'' in Categories taxonomy.
get_term_by('name', 'news', 'category')
// Get term by name ''news'' in Tags taxonomy.
get_term_by('name', 'news', 'post_tag')
// Get term by name ''news'' in Custom taxonomy.
get_term_by('name', 'news', 'my_custom_taxonomy')
By id (term_id, not post_id):
// Get term by id (''term_id'') in Categories taxonomy.
get_term_by('id', 12, 'category')
...
Warning: the example below is wrong (see in this page history):
get_term_by('id', (int)$post->ID, 'taxonomy_name'); // return null
This example try to get a term with ID (term_id) as post_id and in the taxonomy taxonomy_name. This taxonomy not exists and the term_id is wrong.
This is the correct version of this example:
// get_term_by('id', category_id, 'category')
$postCategories = get_the_category($post->ID);
foreach ( $postCategories as $postCategory ) {
$myCategories[] = get_term_by('id', $postCategory->cat_ID, 'category');
}
// OR:
$myCategory = get_term_by('id', $postCategories[0]->cat_ID, 'category');
Since: 2.3.0
get_term_by() is located in wp-includes/taxonomy.php.