arrayswordpresstagsconditional-statementstitle

Wordpress: Conditionally show stripped tag or post title. "Array" gets printed


What I'm trying to achieve: show either the post tag (without the link) or the title.

If a tag exists, that gets printed if it doesn't, the title gets used.

Issue: I've used get_the_tags() as suggested in the Codex to get the tag without the link and that works, yet it gets the word "Array" printed as a prefix, too.

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

What am I missing?


Solution

  • You are echo ing $posttags which is an array. If you echo an array it will echo array as output

    <?php 
     if( has_tag() )
     { 
     This is printing Array as prefix ----> echo $posttags = get_the_tags();
     if ($posttags) {
       foreach($posttags as $tag) {
        echo $tag->name . ' '; 
       }
     } 
     }
     else { echo the_title(); };
    ?>
    

    Please remove that echo , so your new code will be

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

    Hope this helps you