• Is there a way to, if one has the ID of a category, get other data about the category (title, nicenmae, permalink, etc)?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Sure. See some of the examples used in Category Templates.

    Thread Starter flyingrabbit

    (@flyingrabbit)

    Hmmm. I don’t think I’m being clear – I need to be able to do this dynamically, not hard-coded. That is, let’s say I know the ID number of a category’s parent having used get_the_category. The ID is resturned as an integer. I need to be able to take that integer and use it to get the category’ parent as an object so I can get its nicename, etc.

    Use get_the_category() for this (assumes $cat_parent = the category’s parent ID):

    <?php $my_cat = get_the_category($cat_parent); ?>

    $my_cat is now an object holding the values for the various category fields. To display let’s say the category’s name (‘cat_name’ value), use a reference with the first array in $my_cat:

    <?php echo $my_cat[0]->cat_name; ?>

    Values you can access this way:
    cat_ID
    cat_name
    category_nicename
    category_description
    category_parent

    Getting the category permalink is a bit easier:

    <?php $cat_link = get_category_link($cat_parent); ?>

    Thread Starter flyingrabbit

    (@flyingrabbit)

    For some reason this resturns not the category’s parent, but itself.

    $cat = get_the_category();
    $catp = $cat[0]->category_parent;
    echo $catp; // returns "2" - the correct ID of the category's parent
    echo $cat[0]->cat_name; //returns "River"
    $catpar = get_the_category($catp);
    echo $catpar[0]->cat_name; // returns "River" instead of "Current"

    Thread Starter flyingrabbit

    (@flyingrabbit)

    This does it:

    $cat = get_the_category();
    $catp = $cat[0]->category_parent;
    $catID = $cat[0]->cat_ID;
    $catname = $cat[0]->cat_name;
    $catparname = $wpdb->get_var("SELECT cat_name FROM $wpdb->categories WHERE cat_id=".$catp);
    $catparnicename = $wpdb->get_var("SELECT category_nicename FROM $wpdb->categories WHERE cat_id=".$catp);

    So that $catparname returns the parent category name and $catparnicename returns the parent category nicename. These values can be inserted after SELECT to return the various data: http://codex.wordpress.org/Database_Description#Table:_wp_categories

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Get category-related data if I know the category ID’ is closed to new replies.