How To Get Current Category ID PHP?

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:

  1. 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();
  2. 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;
  3. If you have a category slug, you can use the get_category_by_slug() function to retrieve the category object and then use the ID property to retrieve the ID. Here is an example:
    $category_slug = 'my-category';
    $category = get_category_by_slug( $category_slug );
    $category_id = $category->ID;
    

Submit a Comment

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

Subscribe

Select Categories