WordPress: creare e gestire i custom post type

WordPress: creare e gestire i custom post type

WordPress ci permette di creare nuovi tipi di post usando delle impostazioni personalizzate. Questi post vengono chiamati custom post types e rappresentano un'ottima alternativa alla classica tassonomia basata su post e pagine. In questo articolo vedremo come creare e gestire questo tipo di post.

Creare i custom post type

Vogliamo creare un nuovo tipo di post per gestire i libri che abbiamo letto di recente e che ci sono piaciuti di più. Per prima cosa dobbiamo registrare il nuovo tipo di post aggiungendo il seguente codice al file functions.php:


add_action( 'init', 'create_post_type' );

function create_post_type() {
        $args = array(
        'labels' => post_type_labels( 'Libri' ),
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true, 
        'show_in_menu' => true, 
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'has_archive' => true, 
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title',
            'editor',
            'author',
            'thumbnail',
            'excerpt',
            'comments'
        )
    ); 
 
    register_post_type( 'libri', $args );
}

A questo punto il custom post type libri è stato creato, ma mancano le etichette dei menu per gestirlo. Dobbiamo quindi definire queste etichette:

 
function post_type_labels($name) {
    
    return array(
        'name' => _x( $name, 'post type general name' ),
        'singular_name' => _x( 'Libro', 'post type singular name' ),
        'add_new' => __( 'Aggiungi nuovo' ),
        'add_new_item' => __( 'Aggiungi nuovo libro'),
        'edit_item' => __( 'Modifica libro'),
        'new_item' => __( 'Nuovo libro' ),
        'view_item' => __( 'Vedi libro' ),
        'search_items' => __( 'Cerca'. $name ),
        'not_found' =>  __( 'Nessun libro trovato'),
        'not_found_in_trash' => __( 'Non ci sono ' . $name . ' libri nel Cestino' ), 
        'parent_item_colon' => ''
    );
}

Ora dobbiamo fare in modo che il nome del nostro custom post type compaia quando si salva o si aggiorna un post:


add_filter('post_updated_messages', 'post_type_updated_messages');

function post_type_updated_messages( $messages ) {
        global $post, $post_ID;
 
        $messages['libri'] = array(
                0 => '', 
                1 => sprintf( __('Libro aggiornato. <a href="%s">Vedi libro</a>'), esc_url( get_permalink($post_ID) ) ),
                2 => __('Campo personalizzato aggiornato.'),
                3 => __('Campo personalizzato eliminato.'),
                4 => __('Libro aggiornato.'),
                5 => isset($_GET['revision']) ? sprintf( __('Libro salvato dalla revisione da %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
                6 => sprintf( __('Libro pubblicato. <a href="%s">Vedi libro</a>'), esc_url( get_permalink($post_ID) ) ),
                7 => __('Libro salvato.'),
                8 => sprintf( __('Libro inviato. <a target="_blank" href="%s">Anteprima libro</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
                9 => sprintf( __('Libro programmato per: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Anteprima libro</a>'),
                date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
                10 => sprintf( __('Bozza del libro aggiornata. <a target="_blank" href="%s">Anteprima libro</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
        );
 
        return $messages;
}

Gestire i custom post type

Per impostazione predefinita i custom post type non vengono inclusi nel Loop di WordPress. Dobbiamo quindi creare un Loop personalizzato che comprenda anche questo nuovo tipo di post:


<?php
$args = array( 'post_type' => 'libri', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
	<article class="libri" id="libro-<?php the_ID();?>">
		<h2><a href="<?php the_permalink();?>"><?php the_title();?></a></h2>
		<div class="content">
			<?php the_content('Leggi il resto del libro'); ?>
		</div>
	
	</article>
<?php        
endwhile;
?>

Per creare una pagina di archivio o il template di un singolo post, occorre seguire questa nomenclatura dei file nel nostro tema:

  1. archive-{post-type}.php
  2. single-{post-type}.php

Nel nostro caso diventa:

  1. archive-libri.php
  2. single-libri.php

Riferimenti

  1. Documentazione ufficiale di WordPress
  2. La funzione register_post_type()
  3. Custom Post Type UI, un plugin che vi permette di creare i custom post type con una comoda interfaccia grafica
Torna su