I am working on a Wordpress site that has a custom front-end form for submitting posts. I need to add a field in the form to allow users upload a single PDF file along with the post. How can I achieve this?

1 Answer 1


I have done a simple function for that, but i allow all types of media. So this could be a start:

function insert_attachment( $file_handler, $post_id, $settpdf='false' ) {

  // check to make sure its a successful upload
  if ( $_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK ) __return_false();

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

  $attach_id = media_handle_upload( $file_handler, $post_id );

  if ( $settpdf ) update_post_meta( $post_id,'_pdf_id', $attach_id );

  return $attach_id;

and then a input like: <input type="file" name="uploaded_pdf">

You can retrive the meta like this:

$pdf = get_post_meta($post->ID, '_pdf_id', true);
echo '<a href="'.$pdf.'"><?php __('Download PDF','mytheme'); ?></a>';
  • Thanks a lot guys, I'll try it out. One more thing please, how can I display this particular attachment as a link for download when people are viewing the post? Can I set it to be stored in a custom field? That way I can retrieve it using get_post_meta. Thanks again.
    – 3ph
    Commented Jun 5, 2012 at 9:11
  • See updated answer. Commented Jun 5, 2012 at 12:02
  • Thanks Pontus. You guys are the best. It's really amazing that I could get so much assistance. I really appreciate it. Will let you know if the code works well for me.
    – 3ph
    Commented Jun 5, 2012 at 12:05
  • Hi @Pontus, at the risk of sounding greedy, can you please take a look at this other question of mine?: WordPress search via metadata The initial code seems to be baffling everyone so I would like to implement the search form using wp_query as suggested by one of the commenters. What is your opinion? Any pointers or code sample would really be appreciated because I'm not so good at tweaking WP.
    – 3ph
    Commented Jun 5, 2012 at 12:30

Your Answer

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

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