Ad

Wordpress Menu Item Descriptions Into Timber Twig Template

- 1 answer

I've enabled menu item descriptions in the wordpress menu screen options and added descriptions to a few menu items.

Does anyone know how I get them to display in a Timber Twig template?

And a sub-question on that: I assume before the twig part I'll need to add something to functions.php - whenever I try a solution to something that says 'add this to your functions.php' and I put it into the functions.php file supplied with the Timber Starter Theme, I get errors, presumably I'm pasting it at the wrong point in that file? Where's the safe place to add code in there?

Ad

Answer

You can access the description with the post_content property.

Here an example of a possible menu build with Twig - in the a-tags you see {{ item.title }} what is the menu label and {{ item.post_content }} what stands for your description:

<nav id="menu" class="wrapper-menu-main">
<ul class="nav-main">
    {% for item in main_menu.get_items %}

        <li class="nav-main-item {{ item.classes | join(' ') }}">

            <a class="nav-main-link" target="_blank" rel="nofollow noreferrer" href="{{ item.get_link }}">{{ item.title }} {{ item.post_content }}</a>

            {% if item.get_children %}
                <ul class="nav-drop">
                {% for child in item.get_children %}
                    <li class="nav-drop-item {{ child.classes | join(' ') }}">
                        <a class="nav-drop-link" target="_blank" rel="nofollow noreferrer" href="{{ child.get_link }}">{{ child.title }}</a>
                    </li>
                {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>

The main_menu in this line:

{% for item in main_menu.get_items %}

is your twig menu object - it can have a different name in your code of course.

Basically you don't need anything extra in your function.php you just have to get the menu object with twig like:

$context['main_menu'] = new TimberMenu('primary');

Where primary can be a different name in your case depending on how you did registered/named your menu.

Ad
source: stackoverflow.com
Ad