[英]How to use first image in a post as my excerpt thumbnail, not my set featured image
[英]How to get the first image and set it as the post thumbnail?
我有這兩個功能,可以在網上找到並根據需要進行編輯。
我想做的是將wordpress帖子的縮略圖設置為默認值,該縮略圖是先前在函數本身圖像中設置的,或者是嵌入在帖子中的第一張圖像。
但是,某處出了點問題...
wptuts_save_thumbnail($ post_id) ->將帖子的縮略圖設置為默認值, 或者如果尚未設置 (由帖子的作者...)則設置第一張圖片!
function wptuts_save_thumbnail( $post_id ) {
$post_thumbnail = get_post_meta( $post_id, '_thumbnail_id', true );
if (!wp_is_post_revision($post_id)) { // Verify that the post is not a revision
if (empty($post_thumbnail)) { // Check if Thumbnail does NOT exist!
$firstImg = firstImg($post_id); // Get the first image of a post (if available)
if(!$firstImg){ // if available, update the post thumbnail
update_post_meta( $post_id, '_thumbnail_id', 'link to default image here' );
} else { // else -> set thumbnail to default thumbnail
update_post_meta( $post_id, '_thumbnail_id', $firstImg );
}
}
}
}
firstImg($ post _id) ->用於獲取帖子的第一張圖片(按id)
function firstImg($post_id) {
$post = get_post($post_id);
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
$urlLength = strlen(site_url());
$first_img = substr($first_img, $urlLength);
if(empty($first_img)){
return false;
}
return $first_img;
}
這些函數的唯一問題是if(!$firstImg) - else
語句。
該圖片將始終設置為默認值,無論帖子中是否帶有嵌入式圖片。
$firstImg
確實會返回第一個圖像(如果存在),因此問題必須出在兩個if
: if(empty($first_img))
或if(!$firstImg)
。
我試圖尋找問題的任何線索,但沒有發現任何問題。
希望有人可以闡明這個問題:)
提前致謝!
附加信息:
-這兩個函數都寫在我主題的functions.php
中。
-將wptuts_save_thumbnail($post_id)
設置為每次發布新帖子時運行。
-返回時, $first_img
是圖像的相對路徑 (即/wp-contents/uploads/img.jpg),或者為false
。
通過查看代碼,我可以指出的是對firstImg的檢查:
if(!$firstImg){ // if available, update the post thumbnail
update_post_meta( $post_id, '_thumbnail_id', 'link to default image here' );
} else { // else -> set thumbnail to default thumbnail
update_post_meta( $post_id, '_thumbnail_id', $firstImg );
}
似乎返回false,這將為您提供默認圖像。
您可以做的是檢查firstImg函數中轉儲或print_r中$ matches [1] [0]的結果。 還要在返回前檢查$ first_img是什么。 這可以幫助您找到答案,因為似乎您沒有在$ first_img中得到期望的結果。
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.