0

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.

0
file_put_contents($file, $msg_array);

should be

file_put_contents($wp_upload_dir['path'] .'/'. basename( $file ), $msg_array);
  • Does that mean I don't have to run wp_insert_attachment? – Leopold Mar 31 at 12:57
  • No, it does not mean that. wp_insert_attachment attaches your file to post/page with ID of $post_id and inserts the attachment into the media library. DOCS – Qaisar Feroz Mar 31 at 13:08
  • So that takes me to the correct URL but I still don't see the file in the folder. I'm on localhost. I've tried shutting it all down and restarting. Nothing there. – Leopold Mar 31 at 13:40
  • Sorry for my mistake. Updated the answer. Replace 'url' with 'path' in the code. Ref – Qaisar Feroz Mar 31 at 14:06
  • What should the "guid" be then? – Leopold Mar 31 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.