X

How to Attach PDF Files to Post with Custom Metabox File Selection

Snippets by IsItWP

Are you looking for a way to create a new metabox within your post editing screen with a select menu? While there’s probably a plugin for this, we have created a quick code snippet that you can use to attach PDF files to post with custom metabox file selection.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_action("admin_init", "pdf_init");
add_action('save_post', 'save_pdf_link');
function pdf_init(){
	add_meta_box("my-pdf", "PDF Document", "pdf_link", "post", "normal", "low");
	}
function pdf_link(){
	global $post;
	$custom  = get_post_custom($post->ID);
	$link    = $custom["link"][0];
	$count   = 0;
	echo '<div class="link_header">';
	$query_pdf_args = array(
		'post_type' => 'attachment',
		'post_mime_type' =>'application/pdf',
		'post_status' => 'inherit',
		'posts_per_page' => -1,
		);
	$query_pdf = new WP_Query( $query_pdf_args );
	$pdf = array();
	echo '<select name="link">';
	echo '<option class="pdf_select">SELECT pdf FILE</option>';
	foreach ( $query_pdf->posts as $file) {
	   if($link == $pdf[]= $file->guid){
	      echo '<option value="'.$pdf[]= $file->guid.'" selected="true">'.$pdf[]= $file->guid.'</option>';
		 }else{
	      echo '<option value="'.$pdf[]= $file->guid.'">'.$pdf[]= $file->guid.'</option>';
		 }
		$count++;
	}
	echo '</select><br /></div>';
	echo '<p>Selecting a pdf file from the above list to attach to this post.</p>';
	echo '<div class="pdf_count"><span>Files:</span> <b>'.$count.'</b></div>';
}
function save_pdf_link(){
	global $post;
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ return $post->ID; }
	update_post_meta($post->ID, "link", $_POST["link"]);
}
add_action( 'admin_head', 'pdf_css' );
function pdf_css() {
	echo '<style type="text/css">
	.pdf_select{
		font-weight:bold;
		background:#e5e5e5;
		}
	.pdf_count{
		font-size:9px;
		color:#0066ff;
		text-transform:uppercase;
		background:#f3f3f3;
		border-top:solid 1px #e5e5e5;
		padding:6px 6px 6px 12px;
		margin:0px -6px -8px -6px;
		-moz-border-radius:0px 0px 6px 6px;
		-webkit-border-radius:0px 0px 6px 6px;
		border-radius:0px 0px 6px 6px;
		}
	.pdf_count span{color:#666;}
		</style>';
}
function pdf_file_url(){
	global $wp_query;
	$custom = get_post_custom($wp_query->post->ID);
	echo $custom['link'][0];
}

To display the PDF file, you can use this code:

<? pdf_file_url(); ?>
<a href="<? pdf_file_url(); ?>">My PDF File</a>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 20 best WordPress church themes for expanding the flock and how to track affiliate links in Google Analytics.

Comments   Leave a Reply

  1. Fliberty PĂ©rez September 15, 2014 at 10:14 am

    Hi, i need add mor mime type, it’s possible?.

    1. You can do an array for the mime, eg:

      ‘post_mime_type’ => array(‘application/doc’,’application/pdf’)

  2. The isn’t working in loop.

    1. The <? pdf_file_url(); ?> isn't working in loop.

  3. thanks for the code. 🙂

  4. Hi, thank you for the script. I’m using it with a custom post type.
    Display is correct but I can’t save the pdf. Rather, it does save it the first time but then I cannot change it. So I guess it is the ‘save’ function:

    function save_pdf_link(){

    global $post;
    if (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE){ return $post->ID; }
    update_post_meta($post->ID, “link”, $_POST[“link”]);
    }

    My custom type it is called ‘events’. Any idea to make it work?

    Thank You

  5. hi mate, i have a custom post type , listing, i cannot add the above php code to it to display the PDF, when i add this code to functions.php then it gets added for my Posts but not my listings .

    cheers

  6. Hi, since upgrading to WP3.5 this has disappeared from my edit posts/pages, so I can no longer add/edit PDF’s. Can anyone help?

    Thanks, Craig

  7. RESOLVED!!! the snippet missing the “php”

  8. sorry for my english:

    you can integrate this code for a page? what are the changes to be done?

    I did a test back into an post but I do not work that the link is not make the connection with my file help please!!

  9. Great job! But if I try to add multiple Metabox I end up getting the same file for every Custom filed.. I tried making different functions like: function pdf2_ Any ideas?

  10. your code breaks my site.

  11. found it very useful,is there any way to display file name instead of just PDF File:?
    tnx

    1. just replace

      $pdf[]= $file->guid

      with

      $pdf[]= $file->post_title

  12. This is a fantastic post, extremely useful. I am trying to adapt it to enable multiple PDF’s to be selected and then output but struggling, what would be the best way to approach? Any advice appreciated, and thanks again for the article

    1. NĂŁo testei, mas tenta inserir o atributo “multiple” no .

  13. Hi Kevin,

    Got in here upon a search and the pdf_link function came in handy to fix as a part of a custom theme and post types am working on.

    Thank you, you saved me hours.

  14. Leanne Borrowman October 24, 2011 at 4:02 pm

    Kevin I found the solution : 

    Replace the following : 

    echo ‘SELECT pdf FILE’;

    with this : 

    echo ”;

    1. patrick1991groot April 17, 2017 at 2:56 pm

      I know this is a very old post but the right solution would be to pass a empty value i guess!

      Replace the following :

      echo ‘SELECT pdf FILE’;

      with this :

      echo ‘SELECT pdf FILE’;

  15. I can think of so many websites that would benefit from this!

    How would I go about including this into an if statement? So if a pdf has been uploaded, show the link for example…

    1. Could could just replace the pdf_file_url function with the following that would set things up for you. http://pastebin.com/KZmigAyF

      1. Thankyou so much Kevin, just tested it and that works like a charm 🙂 amazing – will re-tweet

        1. Cool glad to hear I could help.

      2. link not working

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!