问题描述
我正在尝试从我使用wp rest api创建的前端表单中上传特色图片,但是它不起作用..这是表单的代码
<form action="" enctype="multipart/form-data" id="form" method="post" name="form">
<div id="upload">
<input id="upload_img" name="upload_img" type="file">
</div>
<input id="submit" name="submit" type="submit" value="Upload">
</form>
if (isset ( $_POST ['submit'] )) {
$api_url = 'http://localhost:8081/api_insert/wp-json/w1/v1/test';
$body = array (
'product_name' => "new test",'description' => "test",'img' => $_FILES['upload_img'],);
$args = array(
'body' => $body,'timeout' => 5000,'headers' => array(),'cookies' => array(),);
$response = wp_remote_post( $api_url,$args );
$body = wp_remote_retrieve_body( $response );
echo $body;
wp_die();
}
最后是API的代码:
add_action( 'rest_api_init',function () {
register_rest_route( 'w1/v1','/test/',array(
'methods' => 'POST','callback' => 'insertProduct'
) );
});
function insertProduct( $data ) {
$title = $data->get_param('product_name') ;
$content = $data->get_param('description') ;
$getimageFile = $data->get_param('img') ;
$product_post = array(
'post_title'=>$title,'post_type'=>'products','post_content'=>$content,'post_status'=> 'publish'
);
$the_post = wp_insert_post( $product_post );
$uploaddir = wp_upload_dir();
$file = $getimageFile['name'];
if ( wp_mkdir_p( $uploaddir['path'] ) ) {
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
}
else {
$uploadfile = $uploaddir['basedir'] . '/' . basename( $file );
}
move_uploaded_file( $getimageFile['tmp_name'],$uploadfile );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename),null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],'post_title' => sanitize_file_name( $filename ),'post_content' => '','post_status' => 'inherit'
);
include_once ABSPATH . 'wp-admin/includes/media.PHP';
include_once ABSPATH . 'wp-admin/includes/file.PHP';
include_once ABSPATH . 'wp-admin/includes/image.PHP';
require_once (ABSPATH . 'wp-includes/pluggable.PHP');
$attach_id = wp_insert_attachment( $attachment,$uploadfile );
$attach_data = wp_generate_attachment_Metadata( $attach_id,$uploadfile );
wp_update_attachment_Metadata( $attach_id,$attach_data );
$res2= set_post_thumbnail( $the_post,$attach_id );
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)