The get_object_term_cache() WordPress PHP function retrieves the cached term objects for the given object ID.
Usage
get_object_term_cache( $id, $taxonomy );
Example:
$terms = get_object_term_cache( 12, 'category' );
Parameters
$id(int) – Required. Term object ID, for example a post, comment, or user ID.$taxonomy(string) – Required. Taxonomy name.
More information
See WordPress Developer Resources: get_object_term_cache()
Examples
Display Post Categories
Retrieve and display the categories of a post with the ID of 45.
$post_id = 45;
$categories = get_object_term_cache( $post_id, 'category' );
if ( $categories ) {
echo 'Post categories: ';
foreach ( $categories as $category ) {
echo $category->name . ', ';
}
}
Get Tags for a Post
Retrieve the tags for a post with the ID of 99.
$post_id = 99;
$tags = get_object_term_cache( $post_id, 'post_tag' );
if ( $tags ) {
foreach ( $tags as $tag ) {
echo 'Tag: ' . $tag->name . '<br>';
}
}
Check if Post has a Specific Category
Check if a post with the ID of 35 has a category with the slug ‘news’.
$post_id = 35;
$categories = get_object_term_cache( $post_id, 'category' );
$has_news_category = false;
if ( $categories ) {
foreach ( $categories as $category ) {
if ( $category->slug == 'news' ) {
$has_news_category = true;
break;
}
}
}
if ( $has_news_category ) {
echo 'This post is in the News category.';
} else {
echo 'This post is not in the News category.';
}
Display User’s Roles
Retrieve and display the roles for a user with the ID of 5.
$user_id = 5;
$roles = get_object_term_cache( $user_id, 'role' );
if ( $roles ) {
echo 'User roles: ';
foreach ( $roles as $role ) {
echo $role->name . ', ';
}
}
Count Posts in a Specific Category
Count the number of posts in a category with the ID of 10.
$category_id = 10;
$posts = get_posts( array(
'category' => $category_id,
'post_type' => 'post',
'post_status' => 'publish',
'nopaging' => true, // retrieve all posts
) );
if ( $posts ) {
echo 'There are ' . count( $posts ) . ' posts in this category.';
} else {
echo 'There are no posts in this category.';
}