Roman Verner
Roman Verner

Reputation: 99

How to display limited number of tags post?

I have a post with tags:b1,b2,b3. But in the category template, I want to show only 2 tags for the post:b1,b2. How can I do it ? Now I use the following code to display tags of the post:

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

What I want to:

enter image description here

Upvotes: 1

Views: 728

Answers (2)

CodeWithRonny
CodeWithRonny

Reputation: 340

This tags only used in wordpress theme in html format. To display 2 tags. If you want to display 4 tags change these code

++$x==4

         <?php $tags = get_tags(); ?>
          <?php if($tags){ ?>
            <?php $x=0; ?>
          <?php foreach ( $tags as $tag ) { ?>
              <a class="badge bg-primary bg-opacity-10 text-primary" href="<?php echo get_tag_link( $tag->term_id ); ?> " rel="tag"><?php echo $tag->name; ?></a>
              <?php if(++$x==2){break;} ?>
          <?php } ?>
          <?php } ?>

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 47992

Updated: Going back to foreach() with a break in it.

<?php
$posttags = get_the_tags();
if($posttags){
    foreach($posttags as $index=>$tag){
        echo '<li>' .$tag->name. '</li>'; // echos while $index == 0 & 1
        if($index>0){break;}  // second iteration ($index==1) breaks the loop
    }
}
?>

Or if the $posttags array does not use numerical keys, you create your own iteration counter:

if($posttags){
    $x=0;
    foreach($posttags as $tag){
        echo '<li>' .$tag->name. '</li>'; 
        if(++$x==2){break;}  // increment and test $x (first $x=1, second $x=2 so break)
    }
}

Upvotes: 1

Related Questions