1

I am basically looping some fields from a gravity form entries.

I using this function below to pass a file url into $filename and convert the file into a media library item, and then attaching that media item to an ACF image field.

But I cannot get PDF's to work. You can manually upload a PDF to an ACF image field. But it fails when using my function.

All other image types work ok with this function, just not PDF.

/**
 * Save image media library and then save the image to acf field
 * @param string $filename
 * @param int $parent_post_id
 * @param string $field
 * @return void
 */
public function create_attachment_and_update_acf_img_field($filename, $parent_post_id, $field) {

    // check the type of file. We'll use this as the 'post_mime_type'.
    $file_type = wp_check_filetype( basename( $filename ), null );
    
    // get the path to the upload directory.
    $wp_upload_dir = wp_upload_dir();

    // prepare an array of post data for the attachment.
    $attachment = [
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
        'post_mime_type' => $file_type['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ];

    // insert the attachment.
    $attach_id = wp_insert_attachment($attachment,$filename,$parent_post_id);

    // make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata($attach_id,$filename);
    wp_update_attachment_metadata($attach_id,$attach_data);

    // update acf field with the attachment id
    update_field($field,$attach_id,$parent_post_id);

}

Many thanks Josh

0

Your Answer

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