WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get a category's title if you know the ID (7 posts)

  1. Ryan Fitzer
    Member
    Posted 7 years ago #

    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?

  2. Ryan Fitzer
    Member
    Posted 7 years ago #

    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;
    ?></a></li>

    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?

  3. Ryan Fitzer
    Member
    Posted 7 years ago #

    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.

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

    Just query the category table in the database.

  5. Kafkaesqui

    Posted 7 years ago #

    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:

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

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

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

  6. Ryan Fitzer
    Member
    Posted 7 years ago #

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

  7. Ryan Fitzer
    Member
    Posted 7 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags