X

Cómo adjuntar archivos PDF a una entrada con la metabox personalizada Selección de archivos

Snippets by IsItWP

¿Está buscando una manera de crear un nuevo metabox dentro de su pantalla de edición de post con un menú de selección? Mientras que probablemente hay un plugin para esto, hemos creado un fragmento de código rápido que se puede utilizar para adjuntar archivos PDF a publicar con la selección de archivos metabox personalizado.

Instrucciones:

Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:

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];
}

Para mostrar el archivo PDF, puede utilizar este código:

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

Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.

Si te ha gustado este fragmento de código, por favor considere revisar nuestros otros artículos en el sitio como: 20 mejores temas de WordPress para iglesias para ampliar el rebaño y cómo realizar un seguimiento de los enlaces de afiliados en Google Analytics.

Comentarios   Deja una respuesta

  1. 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 octubre 24, 2011 en 4:02 pm

    Kevin I found the solution : 

    Replace the following : 

    echo ‘SELECT pdf FILE’;

    with this : 

    echo ”;

    1. patrick1991groot abril 17, 2017 en 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

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!