How to get the current category ID of the active page in WordPress

To get the current category ID of the active page in WordPress, you can use the get_queried_object() function. Here’s how to do it:

In your theme file (e.g., category.php or archive.php), add the following code snippet:

$queried_object = get_queried_object();
$current_category_id = $queried_object->term_id;

This code will get the current queried object and store its term ID (which is the category ID) in the $current_category_id variable.

If you want to display the current category ID, you can use echo:

echo $current_category_id;

Keep in mind that this method works only on category archive pages. If you need to retrieve the category ID for a single post, you can use get_the_category() function:

$categories = get_the_category();
if (!empty($categories)) {
    $current_category_id = $categories[0]->term_id;
    echo $current_category_id;

This code snippet retrieves the categories for the current post and stores the ID of the first category in the $current_category_id variable. If the post has multiple categories, you can loop through the $categories array to retrieve all category IDs.

Leave a Reply

Your email address will not be published. Required fields are marked *