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

Como adicionar descrições de menu em seus temas do WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

O sistema de menu do WordPress tem um recurso interno no qual você pode adicionar descrições aos itens de menu. No entanto, esse recurso está oculto por padrão. Mesmo quando ativado, a exibição não é suportada sem a adição de algum código. A maioria dos temas não foi projetada com as descrições dos itens de menu em mente. Neste artigo, mostraremos como ativar as descrições de menu no WordPress e como adicionar descrições de menu em seus temas do WordPress.

How to add menu descriptions in WordPress themes

Observação: este tutorial exige que você tenha um bom conhecimento de HTML, CSS e desenvolvimento de temas do WordPress.

Quando e por que você gostaria de adicionar descrições de menu?

Alguns usuários acham que adicionar a descrição do menu ajudará no SEO. No entanto, acreditamos que o principal motivo para usá-las é oferecer uma melhor experiência ao usuário em seu site.

As descrições podem ser usadas para informar aos visitantes o que eles encontrarão se clicarem em um item do menu. Uma descrição intrigante atrairá mais usuários para clicar nos menus.

Menu Descriptions

Etapa 1: Ativar descrições de menu

Vá para Appearance ” Menus. Clique no botão Screen Options (Opções de tela ) no canto superior direito da página. Marque a caixa Descriptions (Descrições ).

Enabling menu descriptions in WordPress

Isso ativará o campo de descrições em seus itens de menu. Assim:

Description field added to menu items

Agora você pode adicionar descrições de menu aos itens do menu do WordPress. Entretanto, essas descrições ainda não aparecerão em seus temas. Para exibir as descrições do menu, teremos de adicionar algum código.

Etapa 2: Adicionar a classe walker:

A classe Walker estende a classe existente no WordPress. Basicamente, ela apenas adiciona uma linha de código para exibir descrições de itens de menu. Adicione esse código no arquivo functions.php do seu 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 );
	}
}

Etapa 3. Ativar o Walker no wp_nav_menu

Os temas do WordPress usam a função wp_nav_menu() para exibir menus. Também publicamos um tutorial para iniciantes sobre como adicionar menus de navegação personalizados em temas do WordPress. A maioria dos temas do WordPress adiciona menus no modelo header.php. No entanto, é possível que seu tema tenha usado algum outro arquivo de modelo para exibir menus.

O que precisamos fazer agora é localizar a função wp_nav_menu() em seu tema (provavelmente em header.php) e alterá-la da seguinte forma.


<?php $walker = new Menu_With_Description; ?>

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

Na primeira linha, definimos $walker para usar a classe walker que definimos anteriormente em functions.php. Na segunda linha de código, o único argumento extra que precisamos adicionar aos nossos argumentos wp_nav_menu existentes é 'walker' => $walker.

Etapa 4. Estilizar as descrições

A classe walker que adicionamos anteriormente exibe descrições de itens nesta linha de código:

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

O código acima acrescenta uma quebra de linha ao item de menu adicionando uma tag
e, em seguida, envolve suas descrições em um span com classe sub. Assim:

<li id="menu-item-99" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="http://www.example.com/about/">Sobre<br /><span class="sub">Quem somos nós?</span></a></li>

Para alterar a forma como as descrições aparecem no site, você pode adicionar CSS na folha de estilos do tema. Estávamos testando isso no Twenty Twelve e usamos este CSS.

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

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

Esperamos que este artigo seja útil e que ele o ajude a criar menus com boa aparência e descrições de menu em seu tema. Tem alguma dúvida? Deixe-as nos comentários abaixo.

Recursos adicionais

Como estilizar os menus de navegação do WordPress

Como adicionar itens personalizados a menus específicos do WordPress

Aula de Menus com Descrição de Bill Erickson

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

52 ComentáriosDeixe uma resposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Matthew Blaxton says

    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 ) {

  3. kayvan A.Gilani says

    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.

    • WPBeginner Support says

      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.

      Administrador

  4. yiannis says

    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.

    • WPBeginner Support says

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

      Administrador

  5. Iryna says

    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.

    • Damien Carbery says

      @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.

  6. igorasas says

    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?

  7. Chad says

    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?!?!

  8. Mary Anne says

    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

  9. Paul Renault says

    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?

  10. Barry says

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

  11. Oryan Consulting says

    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!

  12. sambassador says

    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.

  13. Kevin Gilbert says

    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.

  14. Pankaj says

    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.

    • Pankaj says

      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??

  15. DiTesco says

    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!

  16. svet says

    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?

    • David says

      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.

      • Garrett Hyder says

        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.

  17. Samedi Amba says

    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.

  18. Chris Rouse says

    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;
    }

  19. Damien Carbery says

    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 . ”;

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.