您可以为此创建一个小插件,下面是一个小示例,它将尝试根据excerpt
职位字段:
add_action(\'publish_post\', \'auto_featured_image_publish_post\');
function auto_featured_image_publish_post($post, $post_id) {
// check if this post is saved for the first time
if($post->post_date == $post->post_modified) {
// we\'re using the excerpt field, change this to whatever field
// you\'re using
$post = get_post($post_id);
$htmlURL = $post->post_excerpt;
// try to load the webpage
$doc = new DOMDocument();
$doc->loadHTMLFile($htmlURL);
// get all image tags
$images = $doc->getElementsByTagName(\'img\');
// set the first image as featured image for the post, note that
// you will have to handle relative urls, in other words
// if $imageURL isn\'t an absolute url you\'ll need to append the
// value of $post->excerpt
if(count($images)) {
$imageURL = $images[0]->getAttribute(\'src\');
// download image from url
$tmp = download_url($imageURL);
$file = array(
\'name\' => basename($imageURL),
\'tmp_name\' => $tmp
);
// create attachment from the uploaded image
$attachment_id = media_handle_sideload( $file, $post_id );
// set the featured image
update_post_meta($post_id, \'_thumbnail_id\', $attachment_id);
}
}
}
上述方法应该可行,但您当然应该添加代码来处理各种错误,还可能添加代码来检查图像的尺寸和类型是否有效,缩放图像等等。