0
...
$filename = mt_rand( 100,999 ) . '.pdf';
$post_id = wp_insert_post( $post_data );

if ( $post_id ) {
    $pdf_field = get_field_object( $fields['pdf'], $post_id, false, true );

    $fields = array(
        'pdf' => $pdf_field['key'],
    );

    $pdf_field = array(
        'title' => $filename,
        'filename' => $filename,
        'url' => $uploaded_uri,
        'mime_type' => 'application/pdf',
        'type' => 'application',
        'subtype' => 'pdf',
        'icon' => $icon_url,
    );

    update_field( $fields['pdf'], $pdf_field, $post_id );
}
...

The function update_field returns a custom field's post ID. This means that it is successfully inserting the custom field post. But, when we check the respective post, the file is not attached to it.

Any clue what is missing?

  • File upload fields might return all those values, but the stored value of the field is the ID of the attachment for the file. So you need to upload the file to the media library, and then you can set the field value as its ID. – Jacob Peattie Jan 28 at 14:01
  • Okay, the file is already in the Media Library. So, all we have to do now is it set that ID to the value key of the array? – Muhammad Asif Mohtesham Jan 28 at 14:04
  • There is no array. Literally just update_field( 'field_name', $attachment_id, $post_id ); – Jacob Peattie Jan 28 at 14:05
  • I must be a special kind of fool; wasted 6 hours on this like a splendid idiot. :-/ Thank you. – Muhammad Asif Mohtesham Jan 28 at 14:10
  • 1
    Hey, I only know because I've had to go through that before. Only way to learn ;) – Jacob Peattie Jan 28 at 14:12
1

File upload fields might return all those values (depending on the field settings), but those are just based on the media library attachment. The field only actually stores the ID of the attachment for the file as its value. So to populate a File field programatically, you just need to set an attachment ID as the field value.

So once you have the attachment ID, you just need to do this:

update_field( 'field_name', $attachment_id, $post_id );

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.