简体   繁体   中英

Php error “Undefined variable:post” when using “get_post_thumbnail_id($post->ID)”

I have a line of php to get the thumbnail image in my custom wordpress widget:

$footer_recent_thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'footer-recent-thumbnail' );

It produces two php errors:

NOTICE: customwidgets.php:75 - Undefined variable: post
NOTICE: customwidgets.php:75 - Trying to get property of non-object

How can I resolve this? It is the same php I use to get the thumbnail on the blog and it doesn't give an error there.

My guess would be that this code is in a function, like so:

function doSomething($someparams) {
     // ...
     $fotoer_recent_thumb = // .....
     // ...
}

In this case, $post does not exist in this scope, and must be imported by adding the following line inside your function:

global $post;

Alternatively, and more cleanly, pass it as a parameter.

Try this way:

if (has_post_thumbnail()) { 
    $footer_recent_thumb = wp_get_attachment_image_src( 
        get_post_thumbnail_id(get_the_ID()) , 'footer-recent-thumbnail'
    );

    // Do more stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM