WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. leonp
    Member
    Posted 5 years ago #

    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

  2. stvwlf
    Member
    Posted 5 years ago #

    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

  3. johannesholmberg
    Member
    Posted 5 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