Wordpress自动保存远程图像

我们大多数站长文章基本上都不是自己原创的,而是复制粘贴别人的。这样我们在图像的处理上就变得不那么友好。无法自动设置文章中缩略图,因为没有本地图像,唯一的办法就是在把图像下载到我们自己的服务器上。下面的代码就能实现自动保存第一张图像并将其设置成特色图像。

但特别注意的是本代码不适合那种直接入库的采集插件采集的远程图像。(博主鄙视采集站长)

下面是核心代码,您可以将它复制粘贴到您当前主题的functions.php文件里。

add_action('save_post', 'fetch_images');
add_action('publish_post', 'fetch_images');

function fetch_images( $post_ID )  
{
//Check to make sure function is not executed more than once on save
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
return;

if ( !current_user_can('edit_post', $post_ID) ) 
return;

//Check if there is already a featured image; if there is, then quit.
if ( '' != get_the_post_thumbnail() )
return;

remove_action('save_post', 'fetch_images');
        remove_action('publish_post', 'fetch_images');

$post = get_post($post_ID);   

$first_image = '';

if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_image = $matches [1] [0];
}

if (strpos($first_image,$_SERVER['HTTP_HOST'])===false)
{

//Fetch and Store the Image
$get = wp_remote_get( $first_image );
$type = wp_remote_retrieve_header( $get, 'content-type' );
$mirror = wp_upload_bits(rawurldecode(basename( $first_image )), '', wp_remote_retrieve_body( $get ) );

//Attachment options
$attachment = array(
'post_title'=> basename( $first_image ),
'post_mime_type' => $type
);

// Add the image to your media library and set as featured image
$attach_id = wp_insert_attachment( $attachment, $mirror['file'], $post_ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $first_image );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_ID, $attach_id );

$updated = str_replace($first_image, $mirror['url'], $post->post_content);
    
    //Replace the image in the post
    wp_update_post(array('ID' => $post_ID, 'post_content' => $updated));

    // re-hook this function
    add_action('save_post', 'fetch_images');
      add_action('publish_post', 'fetch_images');
}
}

解释下里面用到的钩子,publish_post主要是发布文章时触发钩子,save_post主要保存到草稿或是更新文章是触发钩子。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/auto-save-remote-image.html


撰写评论

您的电子邮箱地址不会被公开。 必填项已用*标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。