2014-09-01 99 views
0

我已经使用要素图像到自定义帖子。我已经写了下面的代码来使用该功能图像到我的插件。显示“注意:未定义的变量:”和“注意:试图获取非对象的属性”

while($q->have_posts()) : $q->the_post(); 

    $newsbox_post_img_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), '', false, ''); 

    $list .= '<li class="news-item"> 
    <table cellpadding="4"> 
     <tr> 
      <td> 
       <img src="'.$newsbox_post_img_src[0].'" width="100" class="img-circle" /> 
      </td> 
      <td>'.get_the_excerpt().'</td> 
     </tr> 
    </table> 
     </li>'; 

endwhile; 

却是露出

未定义的变量...

试图让非对象的属性....

通知。

Error images

请提出一个解决方案。

回答

1

在循环中不需要使用$post->ID。此外,您将需要实际检查$newsbox_post_img_src有事返回,否则将返回一个

试图让非对象

错误的性质。

你的代码应该基本上是这个样子

while($q->have_posts()) : $q->the_post(); 
    $newsbox_post_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), '', false, ''); 

    $list = '<li class="news-item">'; 
    $list .= '<table cellpadding="4">'; 
    $list .= '<tr>'; 
    $list .= '<td>'; 
    if(!empty($newsbox_post_img_src)) { 
     $list .= '<img src="'.$newsbox_post_img_src[0].'" width="100" class="img-circle" />'; 
    }  
    $list .= '</td>'; 
    $list .= '<td>'.get_the_excerpt().'</td>'; 
    $list .= '</tr>'; 
    $list .= '</table>'; 
    $list .= '</li>'; 
    echo $list; 

endwhile; 
wp_reset_postdata(); 
+0

请你解释为什么'$后> ID'不需要? @Pieter Goosen – Bir 2014-09-01 20:19:29

+1

在循环中时,默认情况下使用当前帖子ID。这就是为什么你不需要明确指定一个帖子ID – 2014-09-02 02:53:24

+0

我从WPSE看到你已经发布了这个问题。从那里,我看到你在短代码中使用它。在这种情况下,'echo $ list;'应该是'return $ list;'应该返回shortcode输出,而不是echo'd – 2014-09-02 04:23:18