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. 2012-02-08 - Profesor Yeow

    nice! but.. one thing… this work if I want a unique category? por example, I want the category ID for make a link and go to that category.

  2. 2011-04-21 - Saket Narayan

    Thanks a ton, this works!

  3. 2011-03-09 - patrick

    thanks for info , ill try it first at my new custom themes using get cat id alternative

  4. 2010-08-12 - FileTube.info

    i think functioc.php is better
    because in this way we have to put only single smll line to get the id

    thankyou for sharing

  5. 2010-06-03 - study abroad in US/AUSTRALIA/UK/Canada

    the first method is effective.

  6. 2010-05-19 - Goncorpius

    Thanks , that was i needed

  7. 2009-04-13 - alex koti

    Thanks man, that was what I needed! :)