我有这两个功能,我在网上找到并根据我的需要进行编辑
我要做的是将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
的{{1}}:if(empty($first_img))
或if(!$firstImg)
中。
我试图寻找问题的任何线索,但我一无所获。
希望有人可以对这个问题有所了解:) 提前谢谢!
其他信息:
- 这两个函数都写在我主题的functions.php
中
- wptuts_save_thumbnail($post_id)
设置为每次发布 NEW 帖子时运行
- 返回时,$first_img
是图像的相对路径(即/wp-contents/uploads/img.jpg)或false
。
答案 0 :(得分:1)
我可以通过查看代码来指出,检查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函数中dump或print_r中$ matches [1] [0]的结果。还要在返回之前检查$ first_img是什么时候。这可以帮助您找到答案,因为您似乎没有在$ first_img中获得预期。
希望有所帮助。