Bassem
Bassem

Reputation: 23

Wordpress how to Show The Last Tag Name Only

I searched a lot for an answer but unfortunately i couldn't find one, so i decided to write and ask the question here in the hope of finding a good answer.

Let's say that i have 1~5 tags. Sometimes i have only 3 tags other times i have 5, but i need to show only the last tag name every time.

Here's my attempt:

<?php
$posttags = get_the_tags();
$count=0;
if ($posttags) {
  foreach($posttags as $tag) {
    $count++;
    if (last == $count) {
      echo $tag->name;
    }
  }
}
?>

What can i exchange "last" with? Any suggestions?

Thanks in advance.

Upvotes: 0

Views: 258

Answers (1)

Nahid Hasan
Nahid Hasan

Reputation: 471

its have many solution. the easest solution is using end() function to grab the last element of array. try this code

<?php
$last_tag = get_the_tags();
if ( !empty( $last_tag ) ) {
    $last_tag = end( $last_tag );
    echo $last_tag->name;  
}
?>

now it will solve your eror

Warning: end() expects parameter 1 to be array, boolean given

Upvotes: 1

Related Questions