Allegare un file PDF a un tipo di post personalizzato
Sto cercando di allegare un file PDF a un tipo di post personalizzato.
Ho trovato questo snippet su wpsnipp.com.
Il codice funziona, ma solo per i post normali.
Ho un tipo di post personalizzato chiamato 'events' e non riesco a farlo funzionare.
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">SELEZIONA FILE PDF</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>Seleziona un file PDF dalla lista sopra per allegarlo a questo post.</p>';
echo '<div class="pdf_count"><span>File:</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];
}
E per visualizzare il link nel tema:
<? pdf_file_url(); ?>
Ho cambiato il tipo di post da 'post' a 'events' e la meta box appare nella pagina 'events'.
Fin qui tutto bene.
Salva il PDF la prima volta. E mostra anche il link corretto.
Ma se provo a cambiare il PDF non lo salva. Mostra di nuovo il primo.

Ecco il codice che ho utilizzato nel mio sito WordPress per un custom post type per aggiungere un PDF al post e funziona per me. Prova a modificarlo e utilizzalo. Spero che ti sia utile.
function add_custom_meta_boxes() {
add_meta_box('wp_custom_attachment', 'Brochure Hotel', 'wp_custom_attachment', 'hotel_post', 'normal', 'high');
}
add_action('add_meta_boxes', 'add_custom_meta_boxes');
function wp_custom_attachment() {
wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
$html = '<p class="description">';
$html .= 'Carica il tuo PDF qui.';
$html .= '</p>';
$html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
echo $html;
}
add_action('save_post', 'save_custom_meta_data');
function save_custom_meta_data($id) {
if(!empty($_FILES['wp_custom_attachment']['name'])) {
$supported_types = array('application/pdf');
$arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
$uploaded_type = $arr_file_type['type'];
if(in_array($uploaded_type, $supported_types)) {
$upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
if(isset($upload['error']) && $upload['error'] != 0) {
wp_die('Si è verificato un errore durante il caricamento del file. L\'errore è: ' . $upload['error']);
} else {
update_post_meta($id, 'wp_custom_attachment', $upload);
}
}
else {
wp_die("Il tipo di file che hai caricato non è un PDF.");
}
}
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
Per ottenere il PDF
$hotel_brochure = get_post_meta( $post_id, 'wp_custom_attachment', true );
$hotel_brochure['url']

Funziona. Mancava però questa riga: add_post_meta($id, 'wp_custom_attachment', $upload); sopra questa: update_post_meta($id, 'wp_custom_attachment', $upload); Grazie

Grazie Kuljeet Singh per questa soluzione, funziona perfettamente (con l'osservazione di belacqua). Ho una domanda: Come fare in modo che questa soluzione memorizzi le informazioni del file caricato. Attualmente quando aggiorni il post, la casella personalizzata ti chiede di caricare un file ma non indica che esiste già un file caricato. Grazie in anticipo

WordPress 5.6 qui. Ho provato senza add_post_meta
e funziona. Attenzione però, anche se questo codice sovrascrive i metadati precedentemente aggiornati come previsto, NON sovrascrive il file precedentemente caricato poiché wp_upload_bits
utilizza un nome diverso (qualcosa come file-1.pdf
, file-2.pdf
, file-3.pdf
, e così via). Controlla la cartella wp-content/upload
.

Nota inoltre che PHP 7 valuta $upload['error'] != 0
come false
quando $upload['error']
contiene un messaggio (di tipo stringa). Non è più il caso con PHP 8, ma dovresti comunque utilizzare il controllo di tipo stretto (===
) per evitare comportamenti imprevedibili (tra l'altro $upload['error']
può essere una stringa o false
).

Un'ultima cosa, cita le tue fonti: https://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291 :-P Alcune informazioni aggiuntive riguardo ai miei due commenti precedenti: https://wordpress.stackexchange.com/a/379569/198773.

Ho appena fatto funzionare tutto la scorsa notte utilizzando il codice sopra (e il commento aggiuntivo) e ci sono alcune cose che vorrei aggiungere qui. Innanzitutto, nella sezione "Per ottenere il PDF", 'wpcf-brochure' dovrebbe essere cambiato in 'wp_custom_attachment'. Poi, per rispondere all'ultima domanda dell'OP, per farlo apparire nel backend, ecco la tecnica che ho usato. Prima della riga che dice "echo $html;" in functions.php, aggiungi:
$filearray = get_post_meta( get_the_ID(), 'wp_custom_attachment', true );
$this_file = $filearray['url'];
if($this_file != ""){
$html .= '<div>File corrente:<br>"' . $this_file . '"</div>';
}

Ecco un piccolo aiuto per chi vuole correggere e migliorare la risposta accettata:
define('PREFIX', 'a-good-prefix-');
echo '<input type="file" name="' . PREFIX . 'attachment">';
add_action('save_post', function ($post_id) {
$key = PREFIX . 'attachment';
if (empty($_FILES[$key]['name'])) return;
if (metadata_exists('post', $post_id, $key)) {
unlink(get_post_meta($post_id, $key, true)['file']);
}
$name = $_FILES[$key]['name'];
$tmp = $_FILES[$key]['tmp_name'];
$bits = file_get_contents($tmp);
$upload = wp_upload_bits($name, null, $bits);
if (isset($upload['error']) && $upload['error'] !== false) {
wp_die('Errore di upload: ' . $upload['error']);
} else {
update_post_meta($post_id, $key, $upload);
}
});
Fonti originali: https://code.tutsplus.com/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291.
