Support » Everything else WordPress » Get category id for category.php page

  • I need to code a way, in category.php, to determine the ID of the category that is being browsed. get_the_category() will not work, because it will return an array of ALL categories assigned to the first post.

    e.g., if someone clicks “Fire Department” and that link leads them to “http://ci.champaign.il.us/wordpress/category/city-departments/fire/” (which is a URL for the ‘city-departments > fire’ category page)…
    I need to determine in category.php that the FIRE category is what was clicked, EVEN IF the posts happen to be assigned to more than just the fire category.

    You see, a post might be assigned to the FIRE category and also the HEALTH AND SAFETY category. If I use get_the_category(), it looks like I have no way of knowing that FIRE is the category that is actually being browsed.

    One reason I need to determine what category the visitor clicked is that, in category.php, I’m hoping to then find all the first-level child categories of the category chosen.

    Any idea how to do this? I have gone through the codex for three days trying to figure it out. Basically, I haven’t found a way to determine the category other than looking at posts on the page, which won’t help.

    Sorry if this isn’t making sense… I rewrote the question three times trying to be clearer.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter Paul Kaiser

    (@freakingid)

    I figured this out. You can simply use:

    $cur_cat_id = get_cat_id( single_cat_title("",false) );

    Thanks for this! It’s really helpful.

    Unfortunately it doesn’t work if you have 2 categories having the same name (for example: two subcategories named “Best of” in two diffrent categories, “Article” and “Essay”)

    In such a case, get_cat_id would send you a wrong id for one of the two categories …

    If you have any other idea, I’d be glad to read it 🙂

    I am new to WP, but I have found two ways through to the current (category page’s) category:

    1) There is a “brute force” method: load all categories with get_categories(), then loop through them and check if each one is the category with is_category(). This is obviously a heavy task given that the information we are looking *should* be readily available.

    2) Another method (but I haven’t tested it for stability) is to bring up the $wp_query variable global $wp_query;, if you dump it’s contents you will find out a few different places where it gives you category information:
    – the name of the category (ex: “thecategory”)
    – the ID of the category (ex: 5)
    – the tree of the category (ex: “category/subcategory/thecategory”)
    This is good because it gives you the tools to avoid confusion between categories with the same name and/or slug.

    Hope this helps!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Get category id for category.php page’ is closed to new replies.