Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come aggiungere le descrizioni dei menu nei temi di WordPress

Il sistema di menu di WordPress ha una caratteristica integrata che permette di aggiungere descrizioni alle voci di menu. Tuttavia, questa caratteristica è nascosta in modo predefinito. Anche se abilitata, la visualizzazione non è supportata senza l’aggiunta di codice. La maggior parte dei temi non è stata progettata tenendo conto delle descrizioni delle voci di menu. In questo articolo vi mostreremo come abilitare le descrizioni dei menu in WordPress e come aggiungere descrizioni nei temi di WordPress.

How to add menu descriptions in WordPress themes

Nota: per questo tutorial è necessaria una discreta conoscenza di HTML, CSS e dello sviluppo di temi per WordPress.

Quando e perché aggiungere le descrizioni dei menu?

Alcuni utenti pensano che l’aggiunta di descrizioni ai menu sia utile per la SEO. Tuttavia, riteniamo che il motivo principale per cui si desidera utilizzarle sia quello di offrire una migliore esperienza utente sul proprio sito.

Le descrizioni possono essere utilizzate per dire ai visitatori cosa troveranno facendo clic su una voce di menu. Una descrizione intrigante attirerà più utenti a fare clic sui menu.

Menu Descriptions

Passo 1: Attivare le descrizioni dei menu

Andare su Aspetto ” Menu. Fate clic sul pulsante Opzioni schermo in alto a destra della pagina. Selezionate la casella Descrizioni.

Enabling menu descriptions in WordPress

In questo modo si abilita il campo delle descrizioni nelle voci di menu. In questo modo:

Description field added to menu items

Ora potete aggiungere descrizioni alle voci di menu del vostro menu WordPress. Tuttavia, queste descrizioni non appariranno ancora nei temi. Per visualizzare le descrizioni dei menu, dovremo aggiungere del codice.

Passo 2: Aggiungere la classe walker:

La classe Walker estende la classe esistente in WordPress. In pratica, aggiunge una riga di codice per visualizzare le descrizioni delle voci di menu. Aggiungete questo codice nel file functions.php del tema.

class Menu_With_Description extends Walker_Nav_Menu {
	function start_el(&$output, $item, $depth, $args) {
		global $wp_query;
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
		
		$class_names = $value = '';

		$classes = empty( $item->classes ) ? array() : (array) $item->classes;

		$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
		$class_names = ' class="' . esc_attr( $class_names ) . '"';

		$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

		$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
		$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
		$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
		$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';

		$item_output = $args->before;
		$item_output .= '<a'. $attributes .'>';
		$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
		$item_output .= '<br /><span class="sub">' . $item->description . '</span>';
		$item_output .= '</a>';
		$item_output .= $args->after;

		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
	}
}

Passo 3. Abilitare Walker nel wp_nav_menu

I temi di WordPress utilizzano la funzione wp_nav_menu() per visualizzare i menu. Abbiamo anche pubblicato un tutorial per i principianti su come aggiungere menu di navigazione personalizzati nei temi WordPress. La maggior parte dei temi WordPress aggiunge i menu nel template header.php. Tuttavia, è possibile che il tema abbia utilizzato qualche altro template per visualizzare i menu.

Quello che dobbiamo fare ora è trovare la funzione wp_nav_menu() nel tema (molto probabilmente in header.php) e cambiarla in questo modo.


<?php $walker = new Menu_With_Description; ?>

<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'walker' => $walker ) ); ?>

Nella prima riga impostiamo $walker per utilizzare la classe walker che abbiamo definito in precedenza in functions.php. Nella seconda riga di codice, l’unico argomento aggiuntivo che dobbiamo aggiungere agli argomenti esistenti di wp_nav_menu è 'walker' => $walker.

Passo 4. Stilizzare le descrizioni

La classe walker aggiunta in precedenza visualizza le descrizioni degli elementi in questa riga di codice:

$item_output .= '<br /><span class="sub">' . $item->description . '</span>';

Il codice precedente aggiunge un’interruzione di riga alla voce di menu aggiungendo un tag
e poi wrap le descrizioni in uno span con classe sub. In questo modo:

<li id="menu-item-99" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="http://www.example.com/about/">About<br /><span class="sub">Chi siamo?</span></a></li>

Per modificare l’aspetto delle descrizioni sul sito, è possibile aggiungere del CSS nel foglio di stile del tema. Abbiamo effettuato dei test su Twenty Twelve e abbiamo utilizzato questo CSS.

.menu-item {
border-left: 1px solid #ccc;
}

span.sub { 
font-style:italic;
font-size:small;
}

Ci auguriamo che questo articolo vi sia utile e che vi aiuti a creare menu dall’aspetto gradevole con descrizioni di menu nel vostro tema. Domande? Lasciatele nei commenti qui sotto.

Risorse aggiuntive

Come abbellire i menu di navigazione di WordPress

Come aggiungere elementi personalizzati a menu specifici di WordPress

La classe Menù con descrizione di Bill Erickson

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

51 commentiLeave a Reply

  1. In PHP 8.0 and higher this with throw a critical error.

    You need to find this line:
    function start_el( $output, $item, $depth, $args ) {

    Changing that line to the following should make the error disappear:
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

  2. To Add Menu Descriptions in My WordPress Themes, I did step 1 and 2 of this blog but couldn’t follow in step 3 to move forward and perform the total change.

    • If you cannot find the function in your theme, we would recommend reaching out to your specific theme’s support and they should be able to assist.

      Admin

  3. Hi,
    How to disable product category description in max mega menu ?
    I have already gone to Mega Menu > General Settings and set Menu Item Descriptions to disabled but the problem exists.

    • You would want to reach out to the plugin’s support and they would be able to assist with the setting not working correctly

      Admin

  4. Hi Guys,

    Any ideas how to allow html tags in the description?
    remove_filter(‘nav_menu_description’, ‘strip_tags’);
    this one not work for me.

    • @Iryna: Can you post your code somewhere e.g. pastebin.com.
      Where you call remove_filter() will determine whether it works – it has to be called after the add_filter() call.
      Calling it just before the wp_nav_menu() call might work.

  5. May already be there ready to plug-in? How this hack will work with the theme of “Twenty TwelveVersion: 1.5”
    ? And just as with the plugin wpml?

  6. Hey man, I added the walker class to functions.php, but I cannot find the wp_nav_menu in genesis theme. What am I missing? I have no idea what to do next?!?!

  7. Thank you so much for this tutorial. It was recommended to me and it worked perfectly for making the changes I wanted to make. However, in making these changes, I’ve lost my drop down sub-item menus. Any idea what affected that in the code change?

    Thank you for your time and tutorial

  8. I have implemented the menu descriptions and it worked great. Now my client is asking for a line break within one of the descriptions. I have tried putting a carriage return and inserting a tag into the description field through the admin. It doesn’t appear in the front end. WP removes these edits. Is there a way to remedy this?

  9. Great tutorial guys, just want to know how to implement this on a custom menu displayed using the Custom Menu widget?

  10. Thank you! Been working on WordPress for years and I’ve never even heard of this before. I was looking to remove the descriptions as they were very redundant on the site I’m working on. I looked everywhere for where they were coming from.

    Oh joy!

  11. works!

    but for php 5.4 you’ll have to match the wp walker arguments for the start_el function:

    function start_el( &$output, $object, $depth = 0, $args = array(), $current_object_id = 0 )

    and find replace $item with $object.

  12. Perfect. This was just what I needed to finish up on a site. I had some issues with the CSS, but I finally figured it out and got it working. Thanks for the great articles.

  13. I needed to create same thing and I was totally lost.

    I was planning to do some stupid things to get this thing done.

    thank god I found this post and saved time and stress!

    I simply love this site got to know so much things.

    Thanks you so much for showing the easiest things here.

    • The span tag is coming on sub-menus too.

      its not showing there but it is taking that much of space which makes it look too odd.

      is there any workaround for the same??

  14. This is really a great tutorial and I was wondering if this would work on the Thesis 1.8.5? If not, it would be great if you can provide one. I will most certainly help you put it out there. Thumbs up!

  15. I followed your tutorial and added description to my menu. Thanks! However, when I am in mobile mode menu converts into dropdown menu and menu title and description are connected. For example, if my menu item is “about” and description “more about me”, the mobile version shows “aboutmore about me”. Is there a way to fix this?

    • I had the same problem. Here’s what I did.

      I changed this:
      $description = ! empty( $item->description ) ? ‘<span>’.esc_attr( $item->description ).'</span>’ : ”;

      To this:
      $description = ! empty( $item->description ) ? ‘<br /><span>’.esc_attr( $item->description ).'</span>’ : ”;

      Not sure if it’s the best solution, but it worked for me.

      • Thanks guys, I ran into what SVET and DAVID did with the mobile menu.
        The code seems to have changed my change was simply appending in a span with the dash seperator and in my desktop query simply suppressed it as was unneeded there.

        $item_output .= ‘ – ‘;

        Within my Desktop Only Query set the span to display none;
        @media only screen and (min-width: 740px) {
        header #submenu li span.dash { display:none; }

        Hope that helps, handled my issue nicely.

  16. Thanks for the Great Tutorial. I’ve done the major steps well, as you can see from
    http://ueab.ac.ke/demo/index

    I was stuck with the styling-how do I reduce the space between the Main Menu Label and the description? Your help is greatly appreciated.

  17. Great post. I’ve tried to dig into this before but the previous instructions I found were not this easy to follow. I was able to drop the functions.php code in, figure out how to change the walker class in my header file (different for the theme I use, but straight forward), and get things going in about 15 minutes from start to finish.

    One piece that you might want to add is how to include the right border on the last menu item using the :last-child property.


    .menu-item:last-child {
    border-right: 1px solid #ccc;
    }

  18. Instead of extending Walker_Nav_Menu it would be nice (and easier) if a filter was provided e.g.
    If the core code had:
    $item_output .= apply_filters( ‘walker_nav_menu_description’, $item->description);

    Then the custom filter function would just have:
    return ” . $description . ”;

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.