我正在尝试通过API将base 64编码的图像上载到我的网站媒体库。API返回图像ID,但这些图像在我的媒体库中显示为空白图像。这是我的密码
add_action(\'rest_api_init\', function () {
register_rest_route( \'api/v1\', \'upload_image/\',array(
\'methods\' => \'POST\',
\'callback\' => \'accept_image\'
));
});
function accept_image($request){
$parameters = $request->get_query_params();
$parameters = $parameters[\'image\'];
$decoded = base64_decode(str_replace(\'data:image/png;base64,\',\'\',$parameters));
$upload_dir = wp_upload_dir();
$upload_path = str_replace( \'/\', DIRECTORY_SEPARATOR, $upload_dir[\'path\'] ) . DIRECTORY_SEPARATOR;
$filename = \'my_image.png\';
$hashed_filename = md5( $filename . microtime() ) . \'_\' . $filename;
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );
//HANDLE UPLOADED FILE
if( !function_exists( \'wp_handle_sideload\' ) ) {
require_once( ABSPATH . \'wp-admin/includes/file.php\' );
}
// Without that I\'m getting a debug error!?
if( !function_exists( \'wp_get_current_user\' ) ) {
require_once( ABSPATH . \'wp-includes/pluggable.php\' );
}
// @new
$file = array();
$file[\'error\'] = \'\';
$file[\'tmp_name\'] = $upload_path . $hashed_filename;
$file[\'name\'] = $hashed_filename;
$file[\'type\'] = \'image/png\';
$file[\'size\'] = filesize( $upload_path . $hashed_filename );
// upload file to server
// @new use $file instead of $image_upload
$file_return = wp_handle_sideload( $file, array( \'test_form\' => false ) );
$filename = $file_return[\'file\'];
$attachment = array(
\'post_mime_type\' => $file_return[\'type\'],
\'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename)),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'guid\' => $wp_upload_dir[\'url\'] . \'/\' . basename($filename)
);
$attach_id = wp_insert_attachment( $attachment, $filename );
return $attach_id;
}
我想知道我的问题在哪里,以及如何解决这个问题。我将非常感谢你的帮助。