WordPress: creare un listato di allegati PDF

In WordPress possiamo creare un listato di allegati PDF con semplicità.

WordPress di Gabriele Romanato

In WordPress possiamo creare un listato di allegati PDF con semplicità.

La soluzione è la seguente:


// In functions.php

function pdf_list() {
	global $post;
	$html = '';
	
	$args = array(
		'post_type' => 'attachment',
		'posts_per_page' => -1,
		'post_parent' => $post->ID,
		'post_mime_type' => 'application/pdf'
	);
	
	$pdfs = get_posts( $args );
	if( $pdfs ) {
		$html .= '<ul id="pdf-list">' . "\n";
		foreach( $pdfs as $pdf ) {
			$pdf_url = wp_get_attachment_url( $pdf->ID );
			$pdf_name_arr = explode( '/', $pdf_url );
			$pdf_name = array_reverse( $pdf_name_arr );
			$html .= '<li><a href="' . $pdf_url . '">' . $pdf_name[0] . '</a></li>' . "\n";
		}
		$html .= '</ul>' . "\n";
	}
	
	return $html;
}

add_shortcode( 'pdf-list', 'pdf_list' );

La funzione wp_get_attachment_url() serve a reperire l'URL assoluto dell'allegato. Avrete notato come è sufficiente modificare il parametro post_mime_type della funzione get_posts() per reperire questo tipo di allegato.

Commenti