0

How to properly get only e.g. 3 post tags? My current code:

$post_tags = get_the_tags();
if (!empty($post_tags)) {
    foreach ($post_tags as $tag) {
        echo '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>';
    }
}

1 Answer 1

0

Your question seems similar to this one: how to limit and display tag?

Based on it you can use this code to limit the tags:

$post_tags = get_the_tags();
   shuffle($post_tags); // use this incase you want to pick the tags randomly
   $count = 0;
   if ($post_tags) {
       foreach($post_tags as $tag) {
          $count++;
          echo '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a> ';
          if( $count > 4 ) break;
       }
   }

It will return 3 tags only.

1
  • It works! That code return 5 tags. I changed 4 to 2 and now correctly return 3 tags. Thanks!
    – Avigo
    Sep 29, 2019 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.