Support » Fixing WordPress » Probs with get_the_category – always returns same category

  • Hi,

    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()?

    Thanks,

    Leon

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi

    Even though there is only one category, use this loop

    <?php
    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

    @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?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Probs with get_the_category – always returns same category’ is closed to new replies.