WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to display first category (10 posts)

  1. gillsans
    Member
    Posted 4 years ago #

    How to display first category for a blog post?

    At the top of my post I would like to display 1 category for the post. If I use <?php the_category(', ') ?> it displays all the categories for the post.

    Any info would be much appreciated.

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    You could use get_the_category instead.

    <?php
    $category = get_the_category();
    echo $category[0]->cat_name;
    ?>
  3. gillsans
    Member
    Posted 4 years ago #

    thanks!

  4. gillsans
    Member
    Posted 4 years ago #

    Show the First Category Name Only and create a link?

    <?php
    $category = get_the_category();
    echo $category[0]->cat_name;
    ?>

    How to you create a link to the category?

  5. gillsans
    Member
    Posted 4 years ago #

    Found it...

    <?php $cat = get_the_category(); $cat = $cat[0]; ?>cat_ID);?>"><?php echo $cat->cat_name; ?>

  6. Urosino
    Member
    Posted 4 years ago #

    Could anyone correct the code posted, because it seems to be broken.

    It doesn't create a link to category, only displaying name of it.

  7. MichaelH
    Member
    Posted 4 years ago #

    Must be used "inside The Loop"

    <?php
    $category = get_the_category();
    if ($category) {
      echo '<a href="' . get_category_link( $category[0]->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category[0]->name ) . '" ' . '>' . $category[0]->name.'</a> ';
    }
    ?>

    [moderated - code fixed]

  8. Urosino
    Member
    Posted 4 years ago #

    Thank you Michael,

    I tried (inside the loop) the code you posted above; but I got:

    Parse error: syntax error, unexpected T_ECHO in...

    So I presume there is a problem within this code, or is it me?

    Thank you for your time.

  9. MichaelH
    Member
    Posted 4 years ago #

    Try it again, I added that if at the last second, and incorrectly used a ( instead of a {.

  10. Urosino
    Member
    Posted 4 years ago #

    It works! Thank you again.

Topic Closed

This topic has been closed to new replies.

About this Topic