在WordPress中,你可以使用内置的set_post_thumbnail()
函数来自动设置文章的特色图片。以下是一个简单的代码示例,展示了如何在文章被发布时自动设置特色图片:
// 确保是在发布文章时执行
add_action( ‘publish_post’, ‘auto_set_featured_image’ );
function auto_set_featured_image( $post_ID ) {
// 检查是否已经设置了特色图片
if ( ! has_post_thumbnail( $post_ID ) ) {
// 获取文章内容
$post_content = get_post_field( ‘post_content’, $post_ID );
// 使用正则表达式查找第一张图片作为特色图片
$first_img_src = ”;
$images = [];
preg_match_all(‘//i’ , $post_content, $images);
$first_img_src = $images[1][0];
if ( ! empty( $first_img_src ) ) {
// 设置特色图片
$attachment_id = attachment_url_to_postid( $first_img_src );
if ( $attachment_id ) {
set_post_thumbnail( $post_ID, $attachment_id );
}
}
}
}