我正在尝试添加文本文件作为附件
我首先启用了mime类型
add_filter( \'upload_mimes\', \'my_myme_types\', 1, 1 );
function my_myme_types( $mime_types ) {
$mime_types[\'txt\'] = \'text/plain\';
return $mime_types;
}
提交前端帖子表单后,我通过ajax将文本块发送到服务器,以便将其添加到文本文件中,然后将其作为附件插入
function rt_new_template(){
global $post;
$user_id = absint($_POST["uid"]);
$post_title = sanitize_text_field($_POST["post_title"]);
$post_object = get_page_by_title($post_title, OBJECT, \'chat\');
$post_id = $post_object->ID;
$msg_array = $_POST["msgArray"];
$ext = ".txt";
$file = $user_id . $post_title . $ext;
// $date = date("Y/m/d");
file_put_contents($file, $msg_array);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
\'guid\'=> $wp_upload_dir[\'url\'] .\'/\'. basename( $file ),
\'post_mime_type\' => \'text/plain\',
\'post_title\' => $user_id . $post_title,
\'post_content\' => $user_id . $post_title,
\'post_status\' => \'inherit\'
);
$mid = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($mid) ){
wp_update_attachment_metadata( $mid, wp_generate_attachment_metadata( $mid, $file ) );
}
die();
}
完成后,我可以在管理媒体部分看到新创建的媒体文件。它仅在预览部分显示文档图标。
文件预览中的URL为
http://localhost/wp/wp-content/uploads/224331554033108974.txt
但去那个地址给我一个404,上传文件夹中没有文本文件。