由于wordpress 特色图片的特殊性,这个保存还是比较简单的,为什么说特殊.是因为文章特色图片会与文章一起被保存到wp_posts
数据表中.并且占用一条文章资源,这也就是为什么一些朋友使用wordpress发布文章会发现文章ID并不是紧挨着的,而是相差1个或2个数字.这是由于wordpress的自动保存和特色图片占用了这些资源,当然这里不进行讲解如何将这些东西保存到其他表中或者其他的优化方式.
提示
本次将使用到“方法,该方法需要使用wordpress的内置image处理方法.当然这个只是对于直接使用API独立方式.如果是正常引用,那么这个可以不用管.
//引用地址
require_once( ABSPATH . 'wp-admin/includes/image.php' );
代码示例:
//测试用例数据
$postArr[ 'img' ] = 'http://cdn.meaoo.cn/1475555917_5126.jpg';//图片LOGO
$postArr[ 'userid' ] = '223';//用户ID 这里的ID是指发布者ID
$postArr[ 'catid' ] = '123';//文章分类ID
//远程图片地址
$filepath = $pos[ 'img' ];
//使用函数将远程图片获取到wordpress服务器端
$get = wp_remote_get ( $filepath );
//获取文件格式
$type = wp_remote_retrieve_header ( $get , 'content-type' );
//判断是否图片格式文件
if( is_numeric(strpos( $type,'image'))){
//进行文件重命名,并用MD5进行命名混淆
$file_title = md5 ( date ( 'Ymd' , time () ) . mt_rand ( 1000 , 9999 ) );
//拼接文件地址
$file_name = $file_title . substr ( $filepath , strrpos ( $filepath , "." ) );
//
$file_content = wp_remote_retrieve_body ( $get );
$mirror = wp_upload_bits ( $file_name , null , $file_content );
//写入特色图片需要的数据
$thum[ 'post_author' ] = $userID;//发布者ID
$thum[ 'post_title' ] = $file_title;//文章标题
$thum[ 'post_parent' ] = $aid;
$thum[ 'guid' ] = $mirror[ 'url' ];
$thum[ 'post_type' ] = 'attachment';
$thum[ 'post_mime_type' ] = $type;
$thum[ 'post_status' ] = 'inherit';//文章状态
//以文章形式写入到数据库
$attachment_id = wp_insert_post ( $thum );
set_post_thumbnail ( $aid , $attachment_id );
update_post_meta ( $aid , '_thumbnail_id' , $attachment_id );
update_post_meta($attachment_id,'_wp_attached_file', ltrim( wp_upload_dir()['subdir'],'/') .'/'.$file_name );
$attach_data = wp_generate_attachment_metadata( $attachment_id, ltrim( wp_upload_dir()['path'],'/') .'/'.$file_name );
wp_update_attachment_metadata( $attachment_id, $attach_data );
}