Support » Fixing WordPress » Single Category Title Outside The Loop

  • Resolved travelvice



    I’ve got posts that are always associated with a single category (a country name).

    I’m working outside the loop, and looking obtain the name of the related category for a given post’s ID number.

    I don’t mind a SQL query, as it would match well with others I’ve got in play already.

    The functionality would be the same result as these, which only yield results inside the loop:


    $categoryArray = get_the_category();
     $country = $categoryArray[0]->cat_name;
Viewing 6 replies - 1 through 6 (of 6 total)
  • This is from the codex for another template tag:

    Use OUTSIDE The Loop

    Normally, this tag must be used inside The Loop because it depends on a WordPress PHP variable ($post) that is assigned a value only when The Loop runs. However, you can manually assign this variable and then use the tag just fine.

    I wonder if it works for get_the_category() as well. I can’t see why it shuldn’t. Let me know =)

    huh… I’ll be.

    single_cat_title(POST_ID) doesn’t do anything, but get_the_category(POST_ID) works just fine…

    Interesting. Thanks 🙂

    See the Replace With examples here:

    To get the categor(y|ies) outside The Loop on a single post page, use something like the following when certain of a single category:

    global $post;
    $category = get_the_category($post->ID);
    echo $category[0]->name; // first category name

    or when the possibility of two or more categories exists:

    global $post;
    foreach(get_the_category($post->ID) as $category) {
        echo $category->name . ' ';



    Cool bit of code.

    How do I make it show the last category out of two/three?

    Basically I’m using parent categories for a lot of posts, but some categories have more than one parent category, and I just want to show the child category without it’s parents…


    Thank you for this code;

    global $post;
    foreach(get_the_category($post->ID) as $category) {
        echo $category->name . ',';

    How would you assign “echo $category->name . ‘ ‘;” to another variable so it could be used in another PHP function?

    For example:
    -If I have two cateogories: Stocks and Funds
    -And the echo outputs: Stocks,Funds
    -Can I assign this to antoher field like: $myWordpressCategory so $myWordpressCategory=”Stocks,Funds” and I can use this in another PHP function.

    I’ve tried: $myWordpressCategory = $category->cat_name . ‘,’; but it only returns the last category.

    Thank you,

    How can I write ID of the category instead of name?

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Single Category Title Outside The Loop’ is closed to new replies.