Support » Fixing WordPress » Get a category’s title if you know the ID

  • Resolved Ryan Fitzer


    Is there a way to print out a category’s title if you know the ID#?

    I’m using wp_list_pages for my nav but I want to also hard code the very first category ni the nav as well. The thing is that depending on who uses the template, they may want to name the first cat something different. This is why using the ID would work well. Here is an example:

    <li class="<?php if (is_category('1')) { ?>current_page_item<?php } else { ?>page_item<?php } ?>"><a href="?cat=1">Art</a></li>

    Where it says “Art” I’d like to have a way to print out the category title for the ID #1. Make sense?

Viewing 6 replies - 1 through 6 (of 6 total)
  • I found something that works here in the codex (I had passed it up earlier because it was stated that it needed to be used in the loop, although I’ve used it in the head with success). Here’s what it looks like:

    <li class="<?php if (is_category('1')) { ?>current_page_item<?php } else { ?>page_item<?php } ?>"><a href="?cat=1"><?php
    $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name;

    The only problem is I can’t figure out how to pass a specific cat ID to it. The above example will only return the first category. Anyone have any ideas?

    I’ve also realized that if you view a category archive (?cat=5 for example) the code above will print the name of cat 5 as the category. So you end up with cat 5 (or whatever cat archive your on) listed twice in your nav.

    Is there a way to print out a category’s title if you know the ID#?

    Just query the category table in the database.

    First, I suggest assigning the category values to something other than $cat. Unless you really know what you’re doing with it, it’s never a good idea to reuse WordPress’ global vars.

    Now I can’t guarantee this works everywhere, but one way is to access WordPress’ object cache:

    $category = $wp_object_cache->cache['category'];
    echo $category[1]->cat_name;

    However, Viper’s suggestion is the best (and most foolproof) method:

    global $wpdb;
    $cat_name = $wpdb->get_var("SELECT cat_name from $wpdb->categories WHERE cat_ID = 1");
    echo $cat_name;

    Thanks so much guys! I’ll try and implement this tonight and post back the results.

    The second solution works perfectly. Kafkaesqui, for some reason the first script had no effect, just a blank where the cat name should be (no errors either).

    Thanks again both of you.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Get a category’s title if you know the ID’ is closed to new replies.