WordPress – Uploading PDF from own function is failing

I have a script in my functions php, calling a REST-api – which gives me a totally valid PDF. I am using wp_upload_bits(), and it works just as it should. It places the file in the upload folder with filename and all set.

I use the wp_insert_attachment() function too, and it also does return a valid number as an ID for the newly inserted file.

Read More

On my FTP, I can see that the wp_upload_bits() places the PDF file correctly. But it does now show up in my Media Library, nor for the post I am trying to attach it to.

Should I not be using wp_insert_attachment() for this kind of file?
Works good though for another function I got for images, but not for PDF.

I have added define('ALLOW_UNFILTERED_UPLOADS', true); in my wp-config.php – even though it feels uncalled for. And I have also added pdf as a mimetype, even though it is already “allowed”.

What I am doing wrong here?

// $magic - is the PDF file retrieved from a REST api.
if ($magic) {

    $nameOfTheFile = $docID.'-FILE.pdf';
    // No errors are given
    $attachment = wp_upload_bits( $nameOfTheFile, null, $magic );

    if( !empty( $attachment['error'] ) ) {
        echo '<br>GETTING DOC FAIL '.$attachment['error'].'<br>';
        ob_flush(); flush();
    } else {

        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $filetype = wp_check_filetype( basename( $attachment['file'] ), null );

        $postinfo = array(
            'post_mime_type'    => $filetype['type'],
            'post_title'        => sanitize_file_name($docID),
            'post_excerpt'      => $doc['name'],
            'post_content'      => $doc['name'],
            'post_parent'       => $post_id,
            'post_status'       => 'inherit',
        );
        // print_r($postinfo);
        $filename = $attachment['url'];
        $attach_id = wp_insert_attachment( $postinfo, $filename, $post_id);
        print_r($attach_id); /* ID is successfuly given, but DOES not show up in Media. Even tried omoitting the $post_id, even though it is totallay valid */

        // this might only be required for images? But I tried adding it to see if it was needed for the PDF
        $attach_data = wp_generate_attachment_metadata( $attach_id, $attachment['url'] );
        wp_update_attachment_metadata( $attach_id,  $attach_data );            
    }
}

Related posts