WordPress.org

Ready to get started?Download WordPress

Forums

Show only the first three tags (9 posts)

  1. Varsity
    Member
    Posted 5 years ago #

    How would I go about this? I've tried using get_the_tags(), but while I can set up the PHP correctly to cycle three times, it seems I can't actually access the data...

    $tags = get_the_tags(); if ($tags) { for ($i=0;$i<=2;$i+=1) { echo $tags[$i]->name . ' '; } }

  2. MichaelH
    Member
    Posted 5 years ago #

    From the Codex example at get_the_tags

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    echo $tag->name . ' ';
    }
    }
    ?>

    Or look at get_the_tag_list.

  3. Varsity
    Member
    Posted 5 years ago #

    I'm pretty sure that both of those suggestions will display all of the tags.

  4. MichaelH
    Member
    Posted 5 years ago #

    Sorry missed the goal ;)

    <?php
    $count = 0;
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    $count++;
    if ($count <= 3 ) {
    echo $tag->name . ' ';
    }
    }
    }
    ?>
  5. jdcfsu
    Member
    Posted 5 years ago #

    Is it possible to do this but also make the tags links to the tag archive?

  6. Varsity
    Member
    Posted 5 years ago #

    Yes: use get_tag_link().

  7. jdcfsu
    Member
    Posted 5 years ago #

    Where would you use that? Inserting it in place of get_the_tags() breaks the code.

  8. Varsity
    Member
    Posted 5 years ago #

    This should do the job:

    <?php
    $count = 0;
    $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    $count++;
    if ($count <= 3 ) {
    echo '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a> ';
    }
    }
    }
    ?>
  9. jdcfsu
    Member
    Posted 5 years ago #

    Cool. Thank you.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags