Tassonomia personalizzata specifica per un tipo di post personalizzato

5 lug 2012, 13:22:29
Visualizzazioni: 138K
Voti: 36

Voglio creare una tassonomia personalizzata che si comporti in modo simile al tipo di post come una categoria si comporta con i post predefiniti (sulla base della struttura permalink /%category%/%postname%/) in modo che i post nei tipi di post personalizzati vengano visualizzati come www.example.com/custom-post-type/custom-taxonomy-name/post-name Inoltre, voglio che il meta box delle categorie appaia solo quando aggiungiamo un nuovo post predefinito e non quando aggiungiamo un nuovo post nel tipo di post personalizzato, e che il box della tassonomia personalizzata appaia solo quando aggiungiamo un nuovo post nel tipo di post personalizzato e non quando aggiungiamo un nuovo post predefinito.

0
Tutte le risposte alla domanda 2
5
58

Innanzitutto, se vuoi mostrare il metabox della tassonomia solo al tuo custom post type, registra la tassonomia solo per quel custom post type passando il nome del custom post type come argomento nella funzione register_taxonomy(). In questo modo, il metabox della tassonomia apparirà solo per il custom post type. Se non vuoi mostrare il metabox delle categorie al tuo custom post type, rimuovi il termine category come argomento durante la registrazione del tuo custom post type e includi invece lo slug della tassonomia in questo modo: 'taxonomies' => array( 'post_tag', 'your_taxonomy_name'). Ecco il codice che ho utilizzato per ottenere questo risultato.

Ho registrato una tassonomia personalizzata con slug "themes_categories" sotto il custom post type themes:

function themes_taxonomy() {
    register_taxonomy(
        'themes_categories',  // Il nome della tassonomia. Il nome deve essere in formato slug (non deve contenere lettere maiuscole o spazi).
        'themes',             // nome del post type
        array(
            'hierarchical' => true,
            'label' => 'Themes store', // nome visualizzato
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'themes',    // Questo controlla lo slug base che verrà visualizzato prima di ogni termine
                'with_front' => false  // Non visualizzare la base della categoria prima
            )
        )
    );
}
add_action( 'init', 'themes_taxonomy');

Per modificare il permalink, ho creato la seguente funzione:

function filter_post_type_link( $link, $post ) {
    if ( $post->post_type !== 'themes' )
        return $link;

    if ( $cats = get_the_terms($post->ID, 'themes_categories') )
        $link = str_replace('%themes_categories%', array_pop($cats)->slug, $link);

    return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);

Poi ho registrato un custom post type con slug "themes" come segue:

// Registrazione del Custom Post Type Themes
add_action( 'init', 'register_themepost', 20 );
function register_themepost() {
    $labels = array(
        'name' => _x( 'Themes', 'my_custom_post','custom' ),
        'singular_name' => _x( 'Theme', 'my_custom_post', 'custom' ),
        'add_new' => _x( 'Add New', 'my_custom_post', 'custom' ),
        'add_new_item' => _x( 'Add New ThemePost', 'my_custom_post', 'custom' ),
        'edit_item' => _x( 'Edit ThemePost', 'my_custom_post', 'custom' ),
        'new_item' => _x( 'New ThemePost', 'my_custom_post', 'custom' ),
        'view_item' => _x( 'View ThemePost', 'my_custom_post', 'custom' ),
        'search_items' => _x( 'Search ThemePosts', 'my_custom_post', 'custom' ),
        'not_found' => _x( 'No ThemePosts found', 'my_custom_post', 'custom' ),
        'not_found_in_trash' => _x( 'No ThemePosts found in Trash', 'my_custom_post', 'custom' ),
        'parent_item_colon' => _x( 'Parent ThemePost:', 'my_custom_post', 'custom' ),
        'menu_name' => _x( 'Themes Posts', 'my_custom_post', 'custom' ),
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => false,
        'description' => 'Custom Theme Posts',
        'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'post-formats', 'custom-fields' ),
        'taxonomies' => array( 'post_tag','themes_categories'),
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => get_stylesheet_directory_uri() . '/functions/panel/images/catchinternet-small.png',
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => array( 'slug' => 'themes/%themes_categories%', 'with_front' => FALSE ),
        'public' => true,
        'has_archive' => 'themes',
        'capability_type' => 'post'
    );
    register_post_type( 'themes', $args ); // massimo 20 caratteri, non può contenere lettere maiuscole e spazi
}

Ci sono alcune cose da ricordare durante la registrazione di un custom post. Cambia il parametro "has_archive" con lo slug del custom post type e il nome dello slug rewrite come 'slug' => 'custom_post_type_slug/%taxonomy_slug%.

Ora, quando aggiungi un nuovo post type nella pagina del post type corretto, vedrai il permalink come http://www.example.com/wordpress/themes/%themes_categories%/post-name/. Se la tassonomia personalizzata per questo post non è selezionata, il permalink rimarrà http://www.example.com/wordpress/themes/%themes_categories%/post-name/, che mostrerà poi una richiesta errata.

Per correggere questo, creiamo un termine predefinito nella tassonomia personalizzata (come "uncategorized" nelle categorie).

Aggiungi questo a functions.php:

function default_taxonomy_term( $post_id, $post ) {
    if ( 'publish' === $post->post_status ) {
        $defaults = array(
            'themes_categories' => array('other'),
        );
        $taxonomies = get_object_taxonomies( $post->post_type );
        foreach ( (array) $taxonomies as $taxonomy ) {
            $terms = wp_get_post_terms( $post_id, $taxonomy );
            if ( empty($terms) && array_key_exists( $taxonomy, $defaults ) ) {
                wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
            }
        }
    }
}
add_action( 'save_post', 'default_taxonomy_term', 100, 2 );

Ora, quando la tassonomia personalizzata è lasciata vuota, il permalink diventa automaticamente http://www.example.com/wordpress/themes/other/post-name/.

Infine, non dimenticare di svuotare le rewrite cliccando sul pulsante "Salva modifiche" nella sezione delle impostazioni dei permalink nel backend di WordPress, altrimenti verrai reindirizzato a un errore 404. Spero che questo ti sia d'aiuto.

5 lug 2012 17:52:03
Commenti

Ehi, ho avuto un problema... quando generiamo il link all'archivio della tassonomia usando echo get_the_term_list( $post->ID, $taxonomy, '', ', ', '' ); allora il link appare come www.example.com/taxonomy-term e non come www.example.com/themes/taxonomy-term. Penso che dobbiamo scrivere una regola HTACESS per questo.

Saurabh Goel Saurabh Goel
6 lug 2012 16:49:34

+1, spiegazione fantastica, seguita passo dopo passo e funziona, testato su WordPress 3.4.2

TechAurelian TechAurelian
23 ott 2012 22:27:22

Mi chiedevo: devi aggiungere la tassonomia personalizzata all'array delle tassonomie quando registri un custom post type? Perché sembra funzionare anche senza aggiungerla lì (se hai già registrato una tassonomia per il custom post type). Solo curiosità.

trainoasis trainoasis
8 mar 2017 09:52:43

Ho provato con il plugin CPT UI continuando a usare il tuo rewrite per modificare l'URL. Tutto sembra a posto, gli URL sono tutti corretti e ho resettato i permalink, ma i post effettivi restituiscono un errore 404. :( EDIT: non importa. Ho rimosso Hierarchical dalla tassonomia e mi sono assicurato di salvare le cose nell'ordine corretto, e ora i post sembrano funzionare. Evviva!

Garconis Garconis
17 mag 2018 22:53:26

Forse una cosa utile da notare ora, la funzione 'register_taxonomy' richiede che l'argomento 'show_in_rest' sia TRUE per poter utilizzare il nuovo editor a blocchi di WordPress.

Lee Lee
8 mag 2024 18:30:24
0

ad esempio, registrare una tassonomia personalizzata MY_NEW_CARSS per i custom post type:

$my_taxon_name  = 'MY_NEW_CARSS';
$my_post_types  = array('SUB_CAT_1','SUB_CAT_2','SUB_CAT_3');


//REGISTRA UNA TASSONOMIA PERSONALIZZATA ( http://codex.wordpress.org/Function_Reference/register_taxonomy )
//Se vuoi registrare un post type GERARCHICO (con genitore), leggi questo avviso: https://codex.wordpress.org/Function_Reference/register_post_type#hierarchical
add_action( 'init', 'my_f32' ); function my_f32() { 
    register_taxonomy( $GLOBALS['my_taxon_name'], array(), 
        array( 
            'label'=>$GLOBALS['my_taxon_name'],     'public'=>true, 'show_ui'=>true,  'show_admin_column'=>true,   'query_var'=>true,
            'hierarchical'=>true,   'rewrite'=>array('with_front'=>true,'hierarchical'=>true),  
             ));
}

//REGISTRA UN CUSTOM POST TYPE ( http://codex.wordpress.org/Function_Reference/register_post_type )
add_action( 'init', 'myf_63' );function myf_63() { 

    foreach ($GLOBALS['my_post_types'] as $each_Type)       {
            register_post_type( $each_Type, 
                array( 
                    'label'=>$each_Type,     'labels' => array('name'=>$each_Type.' pagine', 'singular_name'=>$each_Type.' pagina'),        'public' => true,   'publicly_queryable'=> true,      'show_ui'=>true,      'capability_type' => 'post',      'has_archive' => true,      'query_var'=> true,     'can_export' => true,                   //'exclude_from_search' => false,     'show_in_nav_menus' => true,  'show_in_menu' => 'edit.php?post_type=page',//true,     'menu_position' => 5,
                    'hierarchical' =>true,
                    'supports' =>array( 'page-attributes', 'title', 'editor', 'thumbnail' ), 
                    'rewrite' => array('with_front'=>true, ),     //    'rewrite' => array("ep_mask"=>EP_PERMALINK ...) OR    'permalink_epmask'=>EP_PERMALINK, 
                ));

            register_taxonomy_for_object_type('category',$each_Type);       //categorie standard
            register_taxonomy_for_object_type($GLOBALS['my_taxon_name'] ,$each_Type);   //Categorie personalizzate
    }
}
25 lug 2015 21:32:38