php - 无法将图像附加到 wordpress 中的帖子
问题描述
我正在尝试上传 base64 图像。但图像未附加到帖子。虽然它给出了attachid和post id
我试过 wp_handle_sideupload()
$data = $_POST['base_img'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
//$data1 = base64_decode($data);
$img = str_replace( 'data:image/png;base64,', '', $data );
$img = str_replace( ' ', '+', $img );
$data1 = base64_decode( $img );
$upload_dir = wp_upload_dir();
// @new
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$decoded = $data1;
$filename = 'my-base64-image.png';
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
// @new
$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 ) );
//var_dump($file_return); exit;
$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)
);
$post_id = wp_insert_post($attachment);
$attach_id = wp_insert_attachment( $attachment, $filename );
update_post_meta($post_id,'_thumbnail_id',$attach_id);
set_post_thumbnail( $post_id, $attach_id );
媒体库显示已损坏,并且未插入特色图像。为什么我不能将图像附加到帖子虽然正确的附加 ID 和 dpost id 正在发送
解决方案
推荐阅读
- python-3.x - 编排和调度 Python ETL 脚本
- c# - API Get方法返回带有一些字母的null
- html - 如何使用引导程序 - 切换
- share - 产品共享功能,如亚马逊反应原生
- wpf - 从服务器启动 powershell 脚本到远程计算机
- java - How to remove white border/background from Bitmap in Kotlin?
- python - 将 DatetimeIndex 移动一年会产生意想不到的结果
- typescript - Vuetify - 无法通过打字稿在表格中显示数据
- reactjs - React Router 中 url 参数的 TypeScript 输入
- odbc - Cognos TM1 与 ClickHouse 的连接