The Support Forums will be in read-only mode for a scheduled maintenance window on 01 September 2016 14:00 UTC - 20:00 UTC. More information.

Probs with get_the_category - always returns same category (3 posts)

  1. leonp
    Posted 7 years ago #


    I'm trying to alter what my single.php template outputs depending on the category of the post. I add this code in the loop:

    <?php $allcats = get_the_category(); $postcat = $allcats[0]->cat_name; ?>

    I want $postcat to return the name of the current post's category (posts only have one category). My site has a total of 5 categories.

    I'm finding that the value of $postcat is always 'report', regardless of whether this is the category of the post. 'report' was the last category I added to the site.

    Am I misunderstanding or misusing get_the_category()?



  2. stvwlf
    Posted 7 years ago #


    Even though there is only one category, use this loop

    foreach((get_the_category()) as $allcats) {
        $postcat = $allcats->cat_name;

    The loop will execute once and exit, accomplishing what you want

    from http://codex.wordpress.org/Template_Tags/get_the_category

  3. johannesholmberg
    Posted 7 years ago #

    @leonp I have exactly the same problem! When trying to show the posts category on single.php I'm always getting "Reportage" even though the post I'm showing is NOT "Reportage".

    When showing the categories on index.php everything works fine and the posts get the right categories. This is weird, anybody have a solution?

Topic Closed

This topic has been closed to new replies.

About this Topic