我有AJAX图像上传功能attachment_id
价值我想将其保存为全局变量,并在不同的函数中使用它,该函数用于设置存在后缩略图时的状态。
这就是我到目前为止所做的,但没有工作。
Image upload
function write_here_featured_image_upload() {
//var_dump($_FILES);
// Temporary post id
$post_id = 0;
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
require_once( ABSPATH . \'wp-admin/includes/file.php\' );
require_once( ABSPATH . \'wp-admin/includes/media.php\' );
// Let WordPress handle the upload.
global $attachment_id;
$attachment_id = media_handle_upload(\'file\' , $post_id );
$image_attributes = wp_get_attachment_image_src( $attachment_id, \'thumbnail\' );
echo $image_attributes[0];
die();
}
add_action( \'wp_ajax_write_here_img_upload\', \'write_here_featured_image_upload\' );
Add post function
function write_here_add_new_post() {
$post_id = wp_insert_post($new_post);
//echo "Post Added ".$post_id;
if(isset($attachment_id)){
set_post_thumbnail( $post_id, $attachment_id );
}
}
global $attachment_id
似乎不起作用。正确的方法是什么?
最合适的回答,由SO网友:Mateusz Hajdziony 整理而成
考虑到您对问题的评论,您应该做的是:
AJAX函数应将附件ID返回给客户端,前端脚本应捕获该响应并将附件ID存储在某个位置,或者在提交整个表单时在表单中填充一个隐藏的输入字段-将附件ID添加到帖子中。如果已填充隐藏的输入字段,则附件ID将自动添加到POST提交表单时不要忘记进行一些安全检查-当前用户是否是具有“附件ID”ID的帖子的作者?