[英]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: 我有一行php来获取我的自定义wordpress小部件中的缩略图:
$footer_recent_thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'footer-recent-thumbnail' );
It produces two php errors: 它产生两个php错误:
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.
这是我用来获取博客上的缩略图的相同的php,并没有在那里给出错误。
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: 在这种情况下,此范围中不存在
$post
,必须通过在函数内添加以下行来导入:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.