Search code examples
phpwordpresstwigshortcodetimber

Timber Menu from Shortcode


Is it possible to get menu items in a shortcode like [my_menu slug="1"].

Below is what I tried based on the YouTube shortcode in the docs

<?php
// Called from within an init action hook in functions.php
add_shortcode( 'my_menu', 'my_menu_shortcode' );

function my_menu_shortcode( $atts ) {
    
    if( isset( $atts['slug'] ) ) {
        $slug = sanitize_text_field( $atts['slug'] );
        
        $args = array('depth' => 2,);
        $menu = new Timber\Menu( $slug , $args);           
    
    }else{
        $menu = 'Please Enter a Menu Slug';
    }

   
    return Timber::compile( 'shortcodes/my_menu.twig', array( 'menu' => $menu ) );
}
// my_menu.twig
{% if menu %}

    {{menu}}

   <nav>
    <ul class="nav-main">
        {% for item in menu.items %}
           <a class="nav-main-link" href="{{ item.link }}">{{ item.title }}</a>
        {% endfor %}
    </ul>
</nav>
    

{% endif %}

Solution

  • I had menu.items when I should of been using menu.get_items.

    The below works

    <?php
    // Called from within an init action hook in functions.php
    add_shortcode( 'my_menu', 'my_menu_shortcode' );
    
    function my_menu_shortcode( $atts ) {
        
        if( isset( $atts['slug'] ) ) {
            $slug = sanitize_text_field( $atts['slug'] );
            
            $args = array('depth' => 2,);
            $menu = new Timber\Menu( $slug , $args);           
        
        }else{
            $menu = 'Please Enter a Menu Slug';
        }
          
       
        return Timber::compile( 'shortcodes/mey_menu.twig', array( 'menu' => $menu ) );
    }
    

    and the twig file

    
    {% if menu %}
       <nav>
            <ul class="nav-main">
              {% for item in menu.get_items %}
                    <a href="{{ item.link }}">{{ item.title }}</a>
                {% endfor %}
            </ul>
        </nav>
    {% endif %}