Wordpress foreach 无效参数

Wordpress foreach invalid argument

希望有人能帮我解决这个问题。此代码将税作为我的同位素 filte/items 的 class 输出。它在本地主机上运行良好,但一旦上传它仍然可以运行,但会产生以下错误:

*警告:为行中的 /path-to-file.php 中的 foreach() 提供的参数无效 # *

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
  $termsArray = get_the_terms( $post->ID, "print_type" );  //Get terms for item
  $termsString = ""; //initialize string that will contain the terms
    foreach ( $termsArray as $term ) { // for each term 
    $termsString .= $term->slug.' '; //create a string that has all the slugs 
    }
?> 
   <div class="<?php echo $termsString; ?>"> 
   </div> 
<?php endwhile; ?>

我认为问题出在你的 $post->ID 它未定义。试试这个

<?php 
     $guide = array(
        'post_type' => 'post', //type post type name here
        'posts_per_page' => -1, //number of posts
        );
query_posts($guide); while(have_posts()) : the_post(); ?>
    <?php 
    $cats = get_the_terms(get_the_ID(),'type_terms_name_here');
    if($cats){
     foreach ($cats as $value){
         echo $value->term_id; //call term id
         echo $value->name; //call term name
         echo $value->slug; //call term slug
         echo $value->term_group; //call term_group
         echo $value->term_taxonomy_id; //call term_taxonomy_id
         echo $value->taxonomy; //call term taxonomy type
         echo $value->description; //call term description
         echo $value->count; // call term post count
     }
    }
    ?>
    <?php endwhile; ?>

*Warning: Invalid argument supplied for foreach() in /path-to-file.php on line # *

当您向 foreach 循环提供既不是数组也不是对象的数据时,会出现此警告。只需添加一个 if 条件来检查是否相同即可。

<?php
while ( $the_query->have_posts() ):
    $the_query->the_post(); 
    $termsArray  = get_the_terms( get_the_ID(), "print_type" );  //Get terms for item
    $termsString = ""; //initialize string that will contain the terms

    // Only use foreach for a array or object.
    if( is_array($termsArray) ){
        foreach ( $termsArray as $term ) { // for each term 
            $termsString .= $term->slug.' '; //create a string that has all the slugs 
        }
    }
?>

<div class="<?php echo $termsString; ?>">
</div>

<?php endwhile; ?>