Getting hold of the category when using single.php (5 posts)

  1. mateescu
    Posted 9 years ago #


    On my site (http://www.luxurywatches.name) I have a need to extract the category that the post belongs to, when I am using the single.php file - this would be when I am viewing a specific post under a specific category, meaning that the single.php file is in use.

    When I need the category, I normally use the single_cat_title() function to grab a hold of the category.

    In this case, I need to use the single_cat_title() function in the header.php file. The file single.php will then include the header.php file.
    When I try to view a single post, single_cat_title() in the header.php returns nothing, so it is not set there

    On the other hand, if I try to get a hold of the category in the header.php that is included by the category.php, then it works all right.

    So the bottom line is the followig:
    I use the single_cat_title() to extract the category in the header.php file. If it's the category.php file that includes the header.php file, then everything is OK and I will get the category. But if the header.php file is included by the single.php file, then I cannot get a hold of the category of the post.

    Can someone please help me ?

  2. clublakers
    Posted 9 years ago #

    I believe I'm looking for a similar solution.

    I need a category name to display (without hyperlink) in a Post article.

    If I "view all posts" in a category then "single_cat_title()" will locate and display the category. It will not display if I am viewing the permalink of the Post.


  3. Posts can have multiple categories assigned to them. So what do you want? All the categories, in a loop? Or just the first category that the post is in? Or what?

    You would use the get_the_category() function for this sort of thing, really.

  4. clublakers
    Posted 9 years ago #

    Ooooh, right, thanks Otto. I completely forgot about the option for multiple categories.

    Yeah, first category will do... so I guess it would look like this:

    $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name;

    I'll try that in the post and see if it flies.

  5. clublakers
    Posted 9 years ago #

    fyi that worked, thank you for the direction.

Topic Closed

This topic has been closed to new replies.

About this Topic