wordpress利用代码实现外链图片为特色图片

很多时候,我们想给文章配张好的特色图片,都要经历网上找图–下载图片–上传图片–设置特色图片 这些繁琐的步骤。所以这期福利就是自定义图片为特色图片,你只需获取的仅仅是图片地址。

将以下函数加载到主题functions.php里面:

add_action('submitpost_box', 'iippcc_thumbnail_meta_box');
add_action('save_post', 'iippcc_publish_post');

function iippcc_thumbnail_meta_box() {
$screen = get_current_screen();
$post_type = $screen->post_type;
if ( current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) )
add_meta_box('postimageviaurldiv', __('自定义特色图片'), 'iippcc_thumbnail_meta_box_html', null, 'side', 'low');
}function iippcc_thumbnail_meta_box_html() {
echo '<label for="featured_image_url">';
_e("输入图片地址--图片地址必须带后缀", 'iippcc_textdomain' );
echo '</label> ';
echo '<input type="text" id="featured_image_url" name="featured_image_url" value="" size="30" />';
}function iippcc_check_required_transition($new_status='', $old_status='', $post='') {
global $post_ID;

if ('publish' == $new_status) {
iippcc_publish_post($post_ID);
}
}function iippcc_publish_post($post_id) {

$imageUrl = $_POST['featured_image_url'];

if (get_post_meta($post_id, '_thumbnail_id', true) || get_post_meta($post_id, 'skip_post_thumb', true)) {
return;
}

$thumb_id = iippcc_generate_post_thumb($imageUrl, $post_id);

if ($thumb_id) {
update_post_meta( $post_id, '_thumbnail_id', $thumb_id );
}
}function iippcc_generate_post_thumb ($imageUrl, $post_id) {

$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);

if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
return null;
}

$filename = wp_unique_filename( $uploads['path'], $filename );

$new_file = $uploads['path'] . "/$filename";

if (!ini_get('allow_url_fopen')) {
$file_data = curl_get_file_contents($imageUrl);
} else {
$file_data = @file_get_contents($imageUrl);
}

if (!$file_data) {
return null;
}

file_put_contents($new_file, $file_data);

$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );

$wp_filetype = wp_check_filetype( $filename, $mimes );

extract( $wp_filetype );

if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) {
return null;
}

$url = $uploads['url'] . "/$filename";

$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => null,
'post_title' => $imageTitle,
'post_content' => '',
);

$thumb_id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($thumb_id) ) {
require_once(ABSPATH . '/wp-admin/includes/image.php');

wp_update_attachment_metadata( $thumb_id, wp_generate_attachment_metadata( $thumb_id, $new_file ) );
update_attached_file( $thumb_id, $new_file );

return $thumb_id;
}

return null;

}

代码出自:插件Featured Image Via URL

如果你懒得动手也可安装此插件  效果都是一样的

注意:这种方法会将外链图片加载到本地,所以慎用!

文章转自:i科技

本文共 12 个回复

发表留言,喵!