I'm using the Postie plugin to receive an email to create a post. In that email there will be link(s) to a pdf. I'm using wp_extract_urls and code from this post to try to add the pdf to the media library and hopefully attach it to the post.

So far I'm able to add an entry to the media library, but it doesn't have any content. Here's what I have so far:


    $string = the_content();

    $urls = wp_extract_urls( $string );

    $uploaddir = wp_upload_dir();
    $uploadfile = $uploaddir['path'] . '/' . $filename;

    $contents= file_get_contents($urls);
    $savefile = fopen($uploadfile, 'w');
    fwrite($savefile, $contents);

    $wp_filetype = wp_check_filetype(basename($filename), null );

    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => $filename,
        'post_content' => '',
        'post_status' => 'inherit'

    $attach_id = wp_insert_attachment( $attachment, $uploadfile );

    $filenew = get_post( $attach_id );
    $fullsizepath = get_attached_file( $filenew->ID );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
    wp_update_attachment_metadata( $attach_id, $attach_data );



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.