Vuoi aggiungere la classe antenato ai singoli post? Quando apri la pagina di un singolo post (ad esempio single.php), non ottieni alcuna classe current_page_item o current-page-ancestor sul tuo wp_nav_menu. Inoltre, non puoi dire ai tuoi utenti in quale sezione si trovano attualmente.
Istruzioni:
Tutto quello che devi fare è aggiungere questo codice al file functions.php del tuo tema o in un plugin specifico per il sito:
<?php
function add_single_post_ancestor_nav_class($classes, $item){
global $post;
$is_ancestor = false;
if ( is_single() ) {
if ( $post->post_type != 'post' ) {
// Checks if the custom-post-type label name matches the title of the nav-page-item
$post_type_obj = get_post_type_object($post->post_type);
$post_type_labels = $post_type_obj->labels;
$post_type_name = $post_type_labels->name;
if( $item->title == $post_type_name ) { $is_ancestor = true; }
}
else {
// Checks if one of the single-post categories matches the title of the nav-page-item
$categories = get_categories();
foreach ( $categories as $category ) {
if ( in_category($category->name) && $item->title == $category->name ) { $is_ancestor = true; }
}
}
if( $is_ancestor ){ $classes[] = 'current-page-ancestor'; }
}
return $classes;
}
add_filter('nav_menu_css_class' , 'add_single_post_ancestor_nav_class' , 10 , 2);
?>
Se il nome generico nelle etichette non corrisponde al titolo della pagina, non aggiungerà la classe.
Nota: Se questa è la prima volta che aggiungi snippet di codice in WordPress, consulta la nostra guida su come copiare / incollare correttamente snippet di codice in WordPress, in modo da non rompere accidentalmente il tuo sito.
Se ti è piaciuto questo snippet di codice, prendi in considerazione la possibilità di consultare i nostri altri articoli sul sito come: 7 migliori servizi VPN per utenti WordPress e 12 migliori plugin WordPress per podcast.
Puoi mettere il codice in questa pagina? Non riesco a vederlo...
Aggiornato!