WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 2 down vote accepted

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>';
share|improve this answer
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 Jun 5 '12 at 9:11
See updated answer. – Pontus Abrahamsson Jun 5 '12 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 Jun 5 '12 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 Jun 5 '12 at 12:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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