我最近发布了一个插件,可以导入帖子中找到的任何外部图像,并将其导入媒体库,将其附加到帖子中,并将找到的第一个图像设置为特色图像。
http://wordpress.org/extend/plugins/media-tools/
我正在发布获取外部图像并将其设置为特征图像的基本函数。在插件中,这是通过ajax的管理页面完成的,但正如Milo在回答中提到的,您可以将其添加到save\\u post挂钩中。
function process_image() {
$response = \'\';
$data[] = \'\';
$error = 0;
$img = $this->extract_image( $post );
if( empty( $img ) ) {
$response .= \'No images found <br>\';
die( sprintf( $response . \'<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors\', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : \'no\' ) );
}
/** @var $file string or WP_Error of image attached to the post */
$file = media_sideload_image( $img, (int)$post->ID );
if ( is_wp_error( $file ) ) {
$response .= \'<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>\';
$error++;
} else {
$atts = $this->get_attach( $post->ID );
foreach ( $atts as $a ) {
$img = set_post_thumbnail( $post->ID, $a[\'ID\'] );
if ( $img ) {
$thumb = wp_get_attachment_thumb_url( $a[\'ID\'] );
$response .= \'<img src="\'.esc_url( $thumb ).\'" /><br>\';
$response .= \'<a href="\' . wp_nonce_url( get_edit_post_link( $a[\'ID\'], true ) ) . \'" >\' . get_the_title( $a[\'ID\'] ) . \'</a> Set as Featured Image</p><br>\';
}
}
unset( $atts );
unset( $a );
}
return $response;
}
这并不意味着要复制和粘贴。这是一个如何做到这一点的示例,代码需要根据您的具体情况进行调整。这段代码位于一个类中,在我的插件中通过ajax返回$response变量。
在上述代码中调用的用于提取图像的函数:
/**
* Extracts the first image in the post content
* @param object $post the post object
* @return bool|string false if no images or img src
*/
function extract_image( $post ) {
$html = $post->post_content;
if ( stripos( $html, \'<img\' ) !== false ) {
$regex = \'#<\\s*img [^\\>]*src\\s*=\\s*(["\\\'])(.*?)\\1#im\';
preg_match( $regex, $html, $matches );
unset( $regex );
unset( $html );
if ( is_array( $matches ) && ! empty( $matches ) ) {
return $matches[2];
} else {
return false;
}
} else {
return false;
}
}
调用获取附件的get\\u attach函数:
/**
* Queries for attached images
* @param int $post_id The post id to check if attachments exist
* @return array|bool The 1st attached on success false if no attachments
*/
function get_attach( $post_id ) {
return get_children( array (
\'post_parent\' => $post_id,
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'posts_per_page\' => (int)1
), ARRAY_A );
}