我正在创建一个 Wordpress 主题,我想将帖子中的第一张图片作为缩略图用于 Facebook 的 OG 元标记。
我尝试使用该函数get_the_post_thumbnail()
,但它会生成一个 htmlimg
元素。此外,我想拍摄帖子中的第一张图片,而无需在创建帖子时添加特色图片。
这应该很简单,因为已经为每个帖子生成了所有缩略图,我只是没有做对。
在这里,我为您制作了一些功能,您可以使用它来添加/编辑附件事件。
function set_first_as_featured($attachment_ID){
$post_ID = get_post($attachment_ID)->post_parent;
if(!has_post_thumbnail($post_ID)){
set_post_thumbnail($post_ID, $attachment_ID);
}
}
add_action('add_attachment', 'set_first_as_featured');
add_action('edit_attachment', 'set_first_as_featured');
有很大的改进空间,但这也很有魅力。在每个上传/编辑附件上,功能都会检查帖子是否已经有特色图片。如果没有,则将相关图像设置为特色。每一张下一张图片都将被忽略(因为帖子已经有特色图片)。
也许有人觉得它有帮助(你在我的编码中间找到了解决方案,所以...... :))
我找到了这个解决方案:
$size = 'thumbnail'; // whatever size you want
if ( has_post_thumbnail() ) {
the_post_thumbnail( $size );
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'numberposts' => 1)
);
foreach ( $attachments as $thumb_id => $attachment ) {
echo wp_get_attachment_image($thumb_id, $size);
}
}
我找到了一个解决方案:
wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail' )[0];
它工作正常。
将此代码放入主题的functions.php中:
// make the first image of WordPress post as featured image
function first_image_as_featured() {
global $post, $posts;
$first_img_featured = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img_featured = $matches [1] [0];
if(empty($first_img_featured)){ //Defines a default image
$first_img_featured = "/images/default.jpg";
}
return $first_img_featured;
}
然后在 WordPress 循环中添加以下代码:
<?php
if (has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<?php }
else { ?>
<img src="<?php echo first_image_as_featured(); ?>" />
<?php
}
?>
如果未设置特色图片,则会自动将第一张图片作为特色图片。来源:获取 WordPress 帖子的第一张图片作为特色图片
我已经尝试了上述解决方案但没有成功。因此,我构建了一个新的简单解决方案:
function set_first_as_featured($post_id){
$medias = get_attached_media( 'image', $post_id );
if(!has_post_thumbnail($post_id)) {
foreach ($medias as $media) {
set_post_thumbnail($post_id, $media->ID);
break;
}
}
}
add_action('save_post', 'set_first_as_featured');
当您保存帖子时,此代码将检查它是否有任何缩略图。如果没有,它会将附加到此帖子的第一张图片设置为缩略图。