skip to Main Content

Warning is "Invalid argument supplied for foreach()"

<?php
    $tags = get_the_tags();
    foreach($tags as $tag):?>

        <a href="<?php echo get_tag_link($tag->term_id);?>" class="badge badge-success">
            <?php echo $tag->name;?>
        </a>

    <?php endforeach;?>

2

Answers


  1. Check if your $tags variable is an actual array of elements before trying to loop through it all!..

    ie:

    <?php
    $tags = get_the_tags(array('hide_empty' => false)); // show all tags, even empty 1s
    
    // debug - uncomment below to view output
    /* 
       echo "<pre>";
       print_r($tags);
       echo "</pre>";
    */
    
    if( is_array($tags) )
    {
       foreach($tags as $tag):
        ?>
          <a href="<?php echo get_tag_link($tag->term_id);?>" class="badge badge-success">
             <?php echo $tag->name;?>
          </a>
       <?php 
       endforeach; 
    }else{
      echo "<p>Not an Array!</p>";
    }
    ?>
    
    Login or Signup to reply.
  2. In general, don’t assume that a variable returned from a function will always be an array, you can check this before calling foreach like this:

    $tags = get_the_tags();
    if (is_array($tags) || is_object($tags)) {
        foreach ($tags as $tag) {
            ...
        }
    }
    

    In the specific case of get_the_tags(), this might be enough though:

    $tags = get_the_tags();
    if ($tags) {
        foreach ($tags as $tag) {
            ...
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search