Get Category ID by name and vice versa

Have you ever wanted to find out certain category ID by its name or maybe do that in reverse? Maybe I’m missing something but there’s no method to achieve that via built-in WordPress functions so here is quick and dirty way of getting category ID by category name and vice versa.

Get cat ID by name


<?php
	$category_slug = "myCategory"; // just an example name/slug
	$category_ID = $wpdb->get_var( "SELECT term_id FROM $wpdb->terms WHERE slug = '" . $category_slug . "'" );
?>

Get cat name by ID


<?php
	$category_ID = 1; // just an example ID
	$category_name = $wpdb->get_var( "SELECT name FROM $wpdb->terms WHERE term_id = " . $category_id );
?>

Share with others...

deliciousdiggreddittechnoratifacebooktwittergoogleyahoowikioblinklistsimpyspurl
Comments (5)

Track comments via RSS 2.0 feed. Feel free to post the comment, or trackback from your web site.

  • richard on Jul 12, 2009

    So very helpful! Bookmarked that, always need a useful shortcut like that in theme development.

  • genesys on Sep 2, 2009

    There’s an easier way:
    “get_category_by_slug()”
    eg:

    term_id;
    ?>

    http://codex.wordpress.org/Function_Reference/get_category_by_slug

  • Feeleep on Sep 3, 2009

    Yeah, but that’s not the same. Slug is probably returned as “some-category-name” which is not OK in terms of usability (for example navigation).

  • Rodrigo on Sep 17, 2009

    And what about get_category_by_path()?

  • Feeleep on Sep 17, 2009

    I guess you should find out category slug first. It’s a little bit longer way, maybe I’m wrong…

Leave a Comment

Latest comment by Feeleep

I guess you should find out category slug first. It's a little bit longer way, maybe I'm wrong...

Search

Stay in touch!

Subscribe Subscribe to RSSStay up to date with my blog

Twitter Follow me!Follow me or get followed

iPadCaseDen.com iPadCaseDen.comiPad cases, folio cases and bags review

Advertisement

GraphicRiver ThemeForest