簡體   English   中英

我正在開發一個 wordpress 主題並且有一個警告。 如何解決這個問題

[英]I am developing a wordpress theme and there is a warning. How to resolve this

警告是“為 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;?>

在嘗試遍歷所有元素之前檢查您的 $tags 變量是否是實際的元素數組...

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>";
}
?>

通常,不要假設從 function 返回的變量總是一個數組,您可以在調用foreach之前檢查這一點,如下所示:

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

get_the_tags()的特定情況下,這可能就足夠了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM