我一直在制作一个wordpress插件,它可以获得单独的Instagram照片,然后将它们放入短代码中。但是,短代码显示的图像不是保存在WP图像文件夹中,而是直接来自instagram。它使服务器加载时间大幅增加。
所以我搜索了WP dev论坛,发现这个函数设置了指定帖子的特色图片。
function Generate_Featured_Image( $image_url, $post_id ){
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename;
else $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$res1= wp_update_attachment_metadata( $attach_id, $attach_data );
$res2= set_post_thumbnail( $post_id, $attach_id );
}
我缺少的是我拍摄的照片很快就会更新,之后特色图片不会改变。一旦新的Instagram照片上传,有没有办法更新特色图片?或者只是每个小时左右。非常感谢,伙计们!
答案 0 :(得分:0)
尝试这个
if( !function_exists( 'Generate_Featured_Image' ) ){
function Generate_Featured_Image($image, $post_id, $setthumb='false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$image]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $image, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
if(!$setthumb && $post_meta!=''){
update_post_meta($post_id, $post_meta, array( $attach_id ));
}
return $attach_id;
}
}
未经测试,但您可以查看一下您可以制作file_get_contents
等其他代码。