微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

设置WordPress内容中的第一张图片作为特色图像

之前我们有发布过一篇关于如何自动wordpress内容中的第一张图片作为特色图像的教程,但是目前那个方法已经无效了,今天再分享一个最近刚亲测可以正常使用的方法

我们只需要将以下代码添加到您的主题functions.PHP中,然后保存即可,不过这个只对新发布或者再次保存的文章效果哦。且在代码中我们判断了,如果已经存在或者已经设置了文章的特色图像,那么就不再获取和设置了,如果内容中也没有图片,那就设置图片作为文章的特色图像,这个认图像根据您的情况设置路径。

// 当文章没有设置特色图像时,提取内容中的第一张图片作为特色图像

function set_featured_image_from_content( $post_ID ) {

$post = get_post( $post_ID );

if ( ! has_post_thumbnail( $post_ID ) ) {

$first_img = '';

ob_start();

ob_end_clean();

$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i',$post->post_content,$matches);

$first_img = isset( $matches[1][0] ) ? $matches[1][0] : '';

if ( empty( $first_img ) ) {

// 定义认图像

$first_img = get_template_directory_uri() . "/default.jpg";

}

// 如果找到图片地址,则设置为特色图像

if ( $first_img ) {

$image_id = attachment_url_to_postid( $first_img );

if ( $image_id ) {

set_post_thumbnail( $post_ID,$image_id );

}

}

}

}

add_action( 'save_post','set_featured_image_from_content' );

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐