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

Så här lägger du till beskrivningar av menyer i dina WordPress Themes

WordPress menysystem har en built-in funktion där du kan add to descriptions med menu items. Den här funktionen är dock dold som standard. Även när den är aktiverad stöds inte displayen av dem utan att lägga till lite kod. De flesta teman är inte utformade med beskrivningar av menu-items i åtanke. I den här artikeln visar vi dig hur du aktiverar menybeskrivningar i WordPress och hur du add to menybeskrivningar i your WordPress themes.

How to add menu descriptions in WordPress themes

Note: Denna tutorial kräver att du har en viss förståelse för HTML, CSS och utveckling av teman i WordPress.

När och varför vill du add to menu descriptions?

En del användare tror att sökmotorsoptimering underlättas om man lägger till en menu description. Vi tror dock att det främsta skälet till att du vill använda dem är att erbjuda en bättre upplevelse för användarna på din site.

Beskrivningar kan användas för att berätta för besökarna vad de kommer att hitta om de klickar på ett menu-item. En spännande description kommer att locka fler användare att klicka på menyerna.

Menu Descriptions

Step-by-Step 1: Slå på beskrivningar av menyer

Gå till Appearance ” Menyer. Click on Screen Options button at the top right corner of the page. Kontrollera boxen Descriptions.

Enabling menu descriptions in WordPress

Detta aktiverar fältet för beskrivningar i dina menu-items. Gilla det här:

Description field added to menu items

Nu kan du add menu descriptions till objekten i din WordPress meny. Dessa beskrivningar kommer dock ännu ej att visas i dina themes. För att kunna displayed menu descriptions måste vi add to lite kod.

Step-by-Step 2: Add to walker-klassen:

Walker-klassen utökar den befintliga klassen i WordPress. Den lägger i princip bara till en rad kod för att visa beskrivningar av menu-item. Add denna kod i ditt temas functions.php-fil.

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

Step-by-Step 3. Aktivera Walker i wp_nav_menu

WordPress teman använder wp_nav_menu() funktionen för att displaya menyer. Vi har också publicerat en tutorial för nybörjare om hur man add to custom navigation menus i WordPress Themes. De flesta WordPress teman add menyer i header.php template. Det är dock möjligt att ditt theme kan ha använt någon annan template-fil för att visa menyer.

Vad vi behöver göra nu är att hitta wp_nav_menu( )-funktionen i ditt theme (troligtvis i header.php) och ändra den så här.


<?php $walker = new Menu_With_Description; ?>

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

I den första raden ställer vi in $walker för att använda walker-klassen som vi definierade tidigare i functions.php. I den andra kodraden är det enda extra argumentet som vi behöver add to våra befintliga wp_nav_menu-argument ’walker’ => $walker.

Step-by-Step 4. Styling av beskrivningarna

Walker-klassen som vi addade tidigare visar objektbeskrivningar kl. denna kodrad:

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

Ovanstående kod lägger till en radbrytning till menu-item genom att add to en
taggen och omsluter sedan dina beskrivningar i ett span med klassen sub. Like this:

<li id="menu-item-99" class="menu-item menu-item-type-post_type menu-item-object-page"><a href="http://www.example.com/about/">Om<br /><span class="sub">Vem är vi?</span></a></li>

För att ändra hur dina beskrivningar visas på din site kan du add to CSS i ditt temas stylesheet. Vi testade detta på Twenty Twelve och använde denna CSS.

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

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

Vi hoppas att du kommer att tycka att den här artikeln är användbar och att den hjälper dig att skapa snygga menyer med menybeskrivningar i ditt theme. Har du några frågor? Lämna dem i kommentarer under.

Ytterligare resurser

Så här stylar du menyer för navigation i WordPress

Hur man addar Customize objekt till specifika WordPress-menyer

Bill Ericksons menyer med description-klass

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

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.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

52 kommentarerLämna ett svar

  1. Syed Balkhi

    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

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

    • WPBeginner Support

      Thank you for sharing that for those on PHP 8.

      Administratör

  3. Norman

    Hi,
    How can you make the description clickable too?

    • WPBeginner Support

      We cover that in step 4 :)

      Administratör

  4. kayvan A.Gilani

    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

      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.

      Administratör

  5. yiannis

    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

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

      Administratör

  6. Sergio

    Thank you very much!

    • WPBeginner Support

      You’re welcome :)

      Administratör

  7. Lanka

    Thank you so much, you saved me

  8. JKLYN

    Thanks. Saved my time.

  9. dan

    Can this work with the WP_Bootstrap_Navwalker ?

    as i’ve tried it and it breaks my site….

  10. kalpana

    Thank you so much….was very useful to me….you saved my day

  11. Steven

    how to turn off the description in mobile layout?

  12. Anzani Zahrani

    Hello.. Please Help..
    How to add title category, not using title category description ?

  13. Ido Schacham

    Totally helpful, thanks!

  14. Rahman

    Great Tip but in menu description it does not support html tags. can anyone know about this?

    Thanks

  15. Iryna

    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

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

  16. Max

    Is there anyway for the description not to be hyperlinked?

  17. Ashok

    thanks…it worked. but in menu description it does not support html tags.

  18. igorasas

    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?

  19. Guy

    Thanks for the tip

  20. Phong

    Thank you, this was really helpful to just copy paste this and get the quick picture.

  21. Chad

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

  22. Ksenia

    You expain very well – detailed and clearly. 1 minute and menu items descriptions are ok. Thank you!

  23. Mary Anne

    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

    • WPBeginner Support

      It seems like a CSS issue, we are sorry we couldn’t be more specific. Try using Google Chrome’s developer tools to debug it.

      Administratör

  24. Paul Renault

    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?

      • Paul Renault

        The client wants a line break. Is there a way that I can insert a tag in the description? If I put one in now it gets removed.

  25. Barry

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

  26. Oryan Consulting

    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!

  27. sambassador

    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.

  28. Steve Covello

    You Rock!! Worked perfectly.

  29. Kevin Gilbert

    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.

  30. Jon

    Excellent tip. Worked perfectly!

  31. Jedediah White

    This worked perfectly for me. The class function is perfect too. Thanks a lot!

  32. Pankaj

    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

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

  33. DiTesco

    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!

  34. svet

    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

      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

        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.

  35. Nicola

    Great post – very clear, exactly what I needed and worked perfectly. Thank you!

  36. Samedi Amba

    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.

    • Editorial Staff

      It has to do with the line-height of your .menu a class of your theme. If you reduce that, then the spacing will reduce itself.

      Administratör

  37. Chris Rouse

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

  38. Damien Carbery

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

  39. Cathy Earle

    Great info … going to start adding this to my sites. Thank you!

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.