我在主站点上使用wordpress网站创建了一个插件作为第三方的acomodate系统。所以场景是:
当用户在系统上点击提交时,它也会添加到wordpress网站,它工作正常,完全没问题。但是当我尝试通过wp_insert_attachment
设置精选图片时,请让我提供一个类似
http://xxxxx.com/wp-content/uploads/http://xxxxx.com/system/media/.../xx.jpg
我想要的只是http://xxxxx.com/system/media/.../xx.jpg保存为精选图片,是否可以这样做? 这是我目前的剧本
if($pt == "pictures"){
$filename_url = $_GET["dml_file"];
$mime = wp_check_filetype($filename_url, null);
$data = array(
'post_mime_type' => $mime['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($_GET["dml_file"])),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($data, $filename_url, $pid);
update_post_meta($pid, $custom_field, $attachment_id);
}else{
update_post_meta($pid, $custom_field, $_GET["dml_file"]);
}
我尝试使用file_get_contents
和file_put_contents
在WP安装中创建图像,但我不希望这样。
系统正在提交:
http://user:pass!@localhost/wp-content/plugins/dml3rdparty/dmlsubmit.php?dml_save=save&dml_file=http://xxx.xxx.xxx.xxx/dml/assets/media/Accreditation/download.d15bdf4e9e.jpg&dml_type=Print Quality Photos&dml_description=test|download.jpg&dml_status=publish
答案 0 :(得分:1)
来自wp_insert_attachment
documentation(我的粗体强调):
<强> $文件名强>
(字符串)(可选)服务器上文件的位置。使用绝对路径而不是文件的URI。 文件必须位于上传目录。见wp_upload_dir()
默认值:false
很可能,您可以使用media_handle_sideload()
解决此问题。
答案 1 :(得分:0)
此函数使用cURL获取文件内容:
function my_file_get_contents($url){
$options = array(
CURLOPT_AUTOREFERER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10
);
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
此功能使用上述功能获取图像,将其保存到uploads文件夹,并将其设置为帖子的精选图像:
function my_featured_image($image_url,$post_id){
$upload_dir = wp_upload_dir();
$image_data = my_file_get_contents($image_url);
$filename = strtok($image_url, '?');
$filename = basename($filename);
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);
$post_author = get_post_field("post_author",$post_id);
$attachment = array(
"post_author" => $post_author,
"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);
}
致电:
my_featured_image($image_url,$post_id);