How can I get the current category ID in WordPress?

I’m trying to get the category ID on a category archive page to use in my code. I can get the category name using the single_term_title function, but I need the category ID instead. Is there a way to get the category ID of the current page in WordPress?

To get the category ID of the current page, you can use the get_queried_object function. This function returns the current queried object, which will be the category object if the current page is a category archive page.

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

This method will only work if the current page is a category archive page. If the current page is not a category archive page, the get_queried_object function will return null.

You can use the get_query_var function and pass it the ‘cat’ parameter. This function retrieves a query variable from the query string of the current URL.

$category_id = get_query_var( 'cat' );

Or

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

If you already know the category name, you can use the get_cat_ID function.

$category = single_term_title("", false);
$cat_id   = get_cat_ID( $category );