WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/get cat ID

Description

Retrieve the ID of a category from its name.

Usage

<?php get_cat_ID$cat_name ?>

Parameters

$cat_name
(string) (optional) Default is 'General' and can be any category name.
Default: 'General'

Return Values

(integer if 0, string if ID) 
0 if failure and ID of category on success.

Examples

Basic

This is a very basic example of how to use this function in The_Loop. Replace "Category Name" with the name of your category.

<?php
$category_id = get_cat_ID('Category Name');
 <!-- Start the Loop. -->
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

 <!-- Test if the current post is in category "Category Name". -->
 <!-- If it is, the div box is given the CSS class "post-cat-special". -->
 <!-- Otherwise, the div box is given the CSS class "post". -->

 <?php if ( in_category($category_id) ) { ?>
           <div class="post-cat-special">
 <?php } else { ?>
           <div class="post">
 <?php } ?>
</div>
 <!-- Stop The Loop (but note the "else:" - see next line). -->

 <?php endwhile; else: ?>


 <!-- The very first "if" tested to see if there were any Posts to -->
 <!-- display.  This "else" part tells what do if there weren't any. -->
 <p>Sorry, no posts matched your criteria.</p>


 <!-- REALLY stop The Loop. -->
 <?php endif; ?>

Notes

Previous Function Reference to get the category ID has been deprecated.

Change Log

Since: 1.0.0

Source File

get_cat_ID() is located in wp-includes/category.php.

Related

See also index of Function Reference and index of Template Tags.