Hey there, WordPress lovers! Are you ready for another code-centric adventure? Today, we’re going to learn how to fetch the category of a post using the post’s ID. This comes in super handy when you’re customizing templates or creating unique displays based on category information. Let’s get started!
Our journey begins in the functions.php file of your current WordPress theme. This file is located in your theme’s directory, which usually goes something like this: /wp-content/themes/your-theme/functions.php.
Once you’ve got your functions.php file open and ready, it’s time to add our new function. This function will use the WordPress function get_the_category(), which fetches all categories associated with a post. To make it easier for us, we’ll pass the post’s ID to our function, which will then hand it over to get_the_category(). Let’s see how it’s done:
function get_post_category_by_id( $post_id ) {
// Fetching the categories
$categories = get_the_category( $post_id );
// If categories were found.
if ( ! empty( $categories ) ) {
// Let's just get the first category.
$category = $categories[0];
return $category->name;
}
return false;
}
In this code, we’re fetching all the categories associated with the post and, for simplicity, returning the name of the first category. If no categories are found, we return false.
This function won’t do anything unless we call it. To do so, pass the ID of the post whose category you want to fetch:
$post_id = 123; // Replace with your post ID
$category_name = get_post_category_by_id( $post_id );
if ( $category_name ) {
echo 'The category of the post is: ' . $category_name;
} else {
echo 'No categories found for this post.';
}
You could place this code wherever it suits you, as long as it’s after the function definition.
function get_post_category_by_id( $post_id ) {
// Fetching the categories
$categories = get_the_category( $post_id );
// If categories were found.
if ( ! empty( $categories ) ) {
// Let's just get the first category.
$category = $categories[0];
return $category->name;
}
return false;
}
$post_id = 123; // Replace with your post ID
$category_name = get_post_category_by_id( $post_id );
if ( $category_name ) {
echo 'The category of the post is: ' . $category_name;
} else {
echo 'No categories found for this post.';
}
There you have it! This is how you fetch the category of a post by ID in WordPress without the need for plugins. As you can see, a bit of PHP knowledge can unlock a world of possibilities within WordPress. So, keep learning, keep experimenting, and, as always, happy coding!
Enables the creation of unique, personalized landing pages at scale by offering unlimited placeholders for dynamic content.
Essential for crafting content-rich, unique pages for each visitor or target group, optimizing for local SEO, e-commerce variability, or specific event details.