Aggiungere categorie in custom post WordPress

In questo articolo vi spiegherò come aggiungere categorie in custom post WordPress, inoltre, vi mostrerò come usarle nella pagina che vi interessa.

Aggiungere categorie in un custom post

Facciamo l’esempio di un sito di edilizia in cui vogliamo creare un portfolio.

Creazione custom post

Dovrete prima di tutto creare il vostro custom post, quindi aggiungete questo codice (adattandolo alle vostre esigenze) al file function.php del vostro tema/child theme.

// Custom Post Type PORTFOLIO
function tm_home_portfolio() {
    
    $labels = array(
        'name' 				  => __( 'Portfolio', 'tm' ),
        'singular_name'       => __( 'Portfolio', 'tm' ),
        'menu_name'           => __( 'Portfolio', 'tm' ),
        'all_items'           => __( 'Tutti i cantieri', 'tm' ),
        'add_new'             => __( 'Aggiungi cantiere', 'tm' ),
        'add_new_item'        => __( 'Aggiungi nuovo cantiere', 'tm' ),
        'edit_item'           => __( 'Modifica cantiere', 'tm' ),
        'new_item' 			  => __( 'Nuovo cantiere', 'tm' ),
        'view_item'           => __( 'Visualizza cantiere', 'tm' ),
        'view_items'          => __( 'Visualizza tutte le servizi', 'tm' ),
        'search_items'        => __( 'Cerca cantiere', 'tm' ),
        'not_found'           => __( 'Nessuna cantiere trovato', 'tm' ),
        'not_found_in_trash'  => __( 'Nessuna cantiere trovata nel cestino', 'tm' ),
        'parent_item_colon'   => __( 'cantiere padre', 'tm' ),
        'featured_image'	  => __( 'Immagine in evidenza del cantiere', 'tm' ),
        'set_featured_image'  => __( 'Imposta immagine in evidenza del cantiere', 'tm' ),
        'remove_featured_image'=> __( 'Rimuovi immagine in evidenza del cantiere', 'tm' ),
        'use_featured_image'  => __( 'Usa immagine in evidenza del cantiere', 'tm' ),
        'archives' 		   	  => __( 'Portfolio', 'tm' ),
        'insert_into_item' 	  => __( 'Inserisci il cantiere', 'tm' ),
        'items_list' 		  => __( 'Portfolio', 'tm' ),
    );
    
    $args = array(
        'label'				  => __( 'Portfolio', 'tm' ),
        'labels'			  =>	$labels,
        'description' 		  => 'Creazione dei riquadri per i cantieri',
        'public' 			  => true,
        'publicy_queryable'   => true,
        'show_ui' 			  => true,
        'delete_with_user' 	  => false,
        'show_in_rest' 		  => true,
        'rest_base' 		  => '',
        'rest_controller_class'=> 'WP_REST_Posts_Controller',
        'has_archive' 		  => true,
        'show_in_menu' 		  => true,
        'show_in_nav_menu' 	  => true,
        'exclude_from_search' => true,
        'capability_type' 	  => 'post',
        'map_meta_cap' 		  => true,
        'hierarchical' 		  => true,
        'rewrite' 			  => array( 'slug' => 'portfolio', 'with_front' => true),
        'query_var' 		  => true,
        'supports' 			  => array ( 'title', 'editor', 'thumbnail'),
        'menu_icon'           => 'dashicons-buddicons-activity',
        'taxonomies'          => array( 'category' ),
    );
    
    register_post_type ( "portfolio", $args );
    
}
add_action ('init', 'tm_home_portfolio');
// Custom Post Type PORTFOLIO

L’elemento fondamentale per aggiungere le categorie è:

'taxonomies'          => array( 'category' ),

grazie alla chiave ‘taxonomies’ possiamo aggiungere le categorie a questo post, ma non solo, anche tags o tassionomie personalizzate.

Aggiungere categorie dedicate

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
    if( is_category() ) {
        $post_type = get_query_var('post_type');
        if($post_type)
            $post_type = $post_type;
        else
            $post_type = array('nav_menu_item', 'post', 'portfolio'); // don't forget nav_menu_item to allow menus to work!
        $query->set('post_type',$post_type);
        return $query;
    }
}

Grazie a questa funzione, possiamo avere delle categorie completamente dedicate a questo custom post:

Aggiungere categorie in custom post WordPress

Utilizzo

Ora per ogni custom post (del tipo creato) avrà la possibilità di associare una categoria.

Aggiungere categorie in custom post WordPress

Funzioni utili

Lista di tutte le categorie del custom post

$args = array(
    'type' => 'portfolio',
    'taxonomy' => 'category',
    'orderby' => 'name',
    'order'   => 'ASC'
);

$cats = get_categories($args);

Con questa query posso accedere a tutte le categorie create associate al custom post ‘porfolio’.

$cats conterra quindi nome, descrizione, slug… di ogni categoria inserita.

Ottenere le categoria di un post, tramite post_ID

if (have_posts()) {
    while (have_posts()) {
        the_post();
        $post_categories = get_the_category(get_the_ID());
		}
}

Esempio di utilizzo

<?php get_header();
require_once $_SERVER['DOCUMENT_ROOT'] . "/teknomassetti/wp-content/themes/fb_theme/top-header.php";

$args = array(
    'type' => 'portfolio',
    'taxonomy' => 'category',
    'orderby' => 'name',
    'order'   => 'ASC'
);

$cats = get_categories($args);
?>

<section id="main-container" class="main-container">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <div class="shuffle-btn-group">
                    <label class="active" for="all">
                        <input type="radio" name="shuffle-filter" id="all" value="all" checked="checked">Show All
                    </label>
                    
                    <?php foreach ($cats as $cat){
                        if($cat->slug != "senza-categoria"){?>
                    <label for="<?php echo $cat->slug ?>">
                        <input type="radio" name="shuffle-filter" id="<?php echo $cat->slug ?>" value="<?php echo $cat->slug ?>"><?php echo $cat->name ?>
                    </label>
                    <?php }} ?>
                </div><!-- project filter end -->
                
                
                <div class="row shuffle-wrapper">
                    <div class="col-1 shuffle-sizer"></div>
    
                    <?php if (have_posts()) {
                    while (have_posts()) {
                    the_post();
                    $post_categories = get_the_category(get_the_ID());
                    $concat_slug = "";
                    $categories_names = "";
                    foreach ($post_categories as $post_category){
                        $concat_slug = "&quot;{$post_category->slug}&quot;,";
                        $categories_names = "{$post_category->name}, ";
                    }
                    
                    $concat_slug = substr($concat_slug,0,strlen($concat_slug)-1);
                    $categories_names = substr($categories_names,0,strlen($categories_names)-2);
                    ?>
                    
                    <div class="col-lg-4 col-md-6 shuffle-item" data-groups="[<?= $concat_slug ?>]">
                        <div class="project-img-container">
                            <a class="gallery-popup" href="<?php the_post_thumbnail_url(); ?>">
                                <?php the_post_thumbnail('full', array('class' => 'img-fluid', 'alt' => get_post_meta(get_post_thumbnail_id(get_the_id()), '_wp_attachment_image_alt', true))); ?>
                                <span class="gallery-icon"><i class="fa fa-plus"></i></span>
                            </a>
                            <div class="project-item-info">
                                <div class="project-item-info-content">
                                    <h3 class="project-item-title">
                                        <a href="<?php echo get_post_permalink() ?>"><?php the_title(); ?></a>
                                    </h3>
                                    <p class="project-cat"><?= $categories_names ?></p>
                                </div>
                            </div>
                        </div>
                    </div><!-- shuffle item 1 end -->
                    
                    
                    <?php }} ?>
                </div><!-- shuffle end -->
            </div>
            
            <!--<div class="col-12">
                <div class="general-btn text-center">
                    <a class="btn btn-primary" href="projects.html">View All Projects</a>
                </div>
            </div>-->
        
        </div><!-- Content row end -->
    
    </div><!-- Conatiner end -->
</section><!-- Main container end -->

<?php get_footer(); ?>

Risultato:

E sul pannello di constrollo di wordpress:

Per qualsiasi dubbio o domanda non esitate a scrivere un commento o a mandarci una mail.

Lascia un commento