Bir
Bir

Reputation: 812

Showing " Notice: Undefined variable:" and " Notice: Trying to get property of non-object"

I have used feature image to a custom post. I have wrote the following code to use that feature image to my plugin.

 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;

But it is showing

Undefined variable...

and

Trying to get property of non-object....

notices.

Error images

Please suggest a solution.

Upvotes: 0

Views: 129

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9941

You don't need to use $post->ID when inside the loop. Also, you will need to actually check if $newsbox_post_img_src has something to return, otherwise it will return a

Trying to get property of non-object

error.

Your code should basically look something like this

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();

Upvotes: 1

Related Questions