Nothing found in uploads folder after wp_insert_attachment

by Leopold   Last Updated March 31, 2019 12:08 PM

I'm trying to add a text file as an attachment

I first enabled the mime type

add_filter( 'upload_mimes', 'my_myme_types', 1, 1 );
function my_myme_types( $mime_types ) {
  $mime_types['txt'] = 'text/plain';
  return $mime_types;
}

After submitting the frontend post form, I send the chunk of text to the server via ajax so I can add it to a text file and then insert it as an attachment

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();  
}

After completion I can see the newly created media file in the admin media section. It only shows a document icon in the preview section.

The URL in the preview for the file is

http://localhost/wp/wp-content/uploads/224331554033108974.txt

But going to that address gives me a 404 and there's no text file in the uploads folder.

Tags : attachments


Related Questions



Delete attachment script

Updated May 25, 2015 05:03 AM

Image Caption not showing right way

Updated February 16, 2016 00:15 AM