Getting the current category ID in PHP depends on the context in which you want to retrieve it. Here are a few methods that you can use:
-
If you are on a category archive page, you can use the built-in WordPress function
get_queried_object_id()
to retrieve the ID of the current category. Here is an example:$category_id = get_queried_object_id();
-
If you have a category object, you can use the
ID
property to retrieve the ID of the category. Here is an example:$category = get_category( $category_id ); $category_id = $category->ID;
- If you have a category slug, you can use the
get_category_by_slug()
function to retrieve the category object and then use theID
property to retrieve the ID. Here is an example:$category_slug = 'my-category'; $category = get_category_by_slug( $category_slug ); $category_id = $category->ID;