Cristian Tirado
Cristian Tirado

Reputation: 91

Delete an array element in this foreach loop

I have this code wich I use in Wordpress for listing the tags and the number of times they've been used. Here is the code

<?php
$tags = get_tags( array('orderby' => 'count', 'order' => 'DESC') );
foreach ( (array) $tags as $tag ) { ?>
<li class="list-group-item">
<span class="badge"><?php echo $tag->count; ?></span>
<?php echo $tag->name; ?>
</li>
<?php }
?>

The result is the following:

http://s14.postimg.org/z5qghdes1/result.png

So I want to delete the tag 'Animals' from the list. I've looking in other questions but I could not resolve my problem. Thanks for your answer!

Upvotes: 0

Views: 138

Answers (3)

Pratik Joshi
Pratik Joshi

Reputation: 11693

Use following

<?php
$tags = get_tags( array('orderby' => 'count', 'order' => 'DESC') );
foreach ( (array) $tags as $tag ) { 
  if ($tag->name != "Animals" ) {
?>
<li class="list-group-item">
<span class="badge"><?php echo $tag->count; ?></span>
<?php echo $tag->name; ?>
</li>
<?php 
  }
}
?>

Upvotes: 0

Nathan Dawson
Nathan Dawson

Reputation: 19308

Use the exclude argument for get_tags(). In my example I set the term ID to 5; be sure to replace it with the correct value.

exclude can be an array as well allowing you to exclude multiple tags.

Change:

$tags = get_tags( array( 'orderby' => 'count', 'order' => 'DESC' ) );

To:

$tags = get_tags( array( 
    'orderby' => 'count', 
    'order'   => 'DESC',
    'exclude' => 5,
) );

Upvotes: 3

Hieu Le
Hieu Le

Reputation: 8415

You can update your code as bellow:

<?php
$tags = get_tags( array('orderby' => 'count', 'order' => 'DESC') );
foreach ( (array) $tags as $tag ) { 
  if ($tag->name == "Animals" ) { continue; }
?>
<li class="list-group-item">
<span class="badge"><?php echo $tag->count; ?></span>
<?php echo $tag->name; ?>
</li>
<?php }
?>

Upvotes: 0

Related Questions