Get the Category ID in WordPress

Today I have a quick tip for all the WordPress theme developers. I’m actually working on a theme right now and thought I would share a tip that will make your themes much more user friendly.

Often when developing themes for one reason or another you want the end user to give you the ID for a category. This could be so you could call certain categories, or exclude them, or create custom menus etc. In previous WordPress versions the category ID’s were listed along side the categories so it wasn’t as hard for people to find the ID’s. This isn’t true anymore, and for less savvy template users, finding a category ID may not be so easy. At first I simply decided to give users a chart in the theme options page(you can see this in action in my CheckMate theme), and that works OK. But it isn’t ideal.

No Worries, We Got A Function

That function is get_cat_id() and can make end users life easier. You can use this function to take the category name get it’s ID number to use in functions like query_posts. Now all your users have to do is enter the category name in the theme options panel(or name a category something specific like “video”).

Examples

This is a very basic example of how to use the function.

<?php
$id = get_cat_id('video');
$q = "cat=" . $id;
query_posts($q);
if (have_posts()) : while (have_posts()) : the_post();

the_content();

endwhile; endif;
?>
  1. 11 Jun, 2008 Keith Penton

    Thank you for this information - just what I needed to modify a page template I’m working on (want to include trailers to some posts in certain categories on a page using get_posts(), without messing up existing retrieved post).

  2. 4 Jul, 2008 Jeff

    Thanks for the tip. Well explained & just what I was looking for!

Leave a comment