[英]Php error “Undefined variable:post” when using “get_post_thumbnail_id($post->ID)”
我有一行php來獲取我的自定義wordpress小部件中的縮略圖:
$footer_recent_thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'footer-recent-thumbnail' );
它產生兩個php錯誤:
NOTICE: customwidgets.php:75 - Undefined variable: post
NOTICE: customwidgets.php:75 - Trying to get property of non-object
我該如何解決這個問題? 這是我用來獲取博客上的縮略圖的相同的php,並沒有在那里給出錯誤。
我的猜測是這個代碼在一個函數中,如下所示:
function doSomething($someparams) {
// ...
$fotoer_recent_thumb = // .....
// ...
}
在這種情況下,此范圍中不存在$post
,必須通過在函數內添加以下行來導入:
global $post;
或者,更干凈地將其作為參數傳遞。
試試這種方式:
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.