Get Category ID alternative

August 29th, 2008

Wordpress template tag the_category_id has been deprecated which means it will not work now or in the future. The reason for this is that Wordpress now supports multiple categories.

Here is the solution recommended by the Wordpress team. It displays all the category IDs hooked to the post.

<?php
foreach((get_the_category()) as $category) {
    echo $category->cat_ID . ' ';
} ?>

It’s a bit long and complicated if you just need the first category. The function below is an alternative. It returns the first category ID as a string. Put this function in your functions.php within your theme folder:

function wt_get_category_ID() {
	$category = get_the_category();
	return $category[0]->cat_ID;
}

Call the function below by placing it within the loop in your theme:

wt_get_category_ID();

Short and sweet, is’nt it?

To get all new functions/template tags, install my plugin WP Extra Template Tags.

  1. 2009-04-13 - alex koti

    Thanks man, that was what I needed! :)