Filter which Menu to display

Hello Community,

the theme I’m currently developing has three menu-areas: 1 top menu and 2 footer-menus.

The position can be chosen via Panel:

I want to create 3 snippets now, that display the menus at the respective position in the theme. I try to filter them by the field “Menu Control” but it doesn’t work. Can you tell me, where my mistake is?

<?php 
    $menu = $site->menus()->toStructure(); 
    $menuControl = $menu->menuControl();
?>

<?php if ($menuControl->is('footernav_1')): ?>

    <?php $menuItems = $menu->menuItems()->toPages(); ?>
    
    <?php if ($menuItems->isNotEmpty()) : ?>
            <nav class="footer-menu">
                <h4><?= $menu->menuHeadline()->html() ?></h4>
                <ul>
                    <?php foreach ($menuItems as $menuItem) : ?>
                        <li><a href="<?= $menuItem->url() ?>"><?= $menuItem->title() ?></a></li>
                    <?php endforeach ?>
                </ul>
            </nav>
    <?php endif ?>
<?php endif ?>

I get the error “Call to a member function true() on null”.

$menu in your example is a structure, i.e. a collection, not a single item, so $menuControl won’t give you anything.

Let’s say you want to get the main menu:

<?php 
// all menus defined in the structure
$menus = $site->menus()->toStructure(); 
// find the one where menu_control is `mainmenu`
$mainMenu = $menus->findBy('menu_control', 'main_menu');
if ($mainMenu) {
  // do stuff
}

Note that you have to adapt the field names/values to the ones used in your blueprint (since you haven’t posted them).

Then do the same for your other menus.

Thank you so much for your help @texnixe

Works like a charm now :slight_smile:

<?php 
// all menus defined in the structure
$menus = $site->menus()->toStructure(); 
// find the one where menuControl is `footer_menu_1`
$footerMenu1 = $menus->findBy('menuControl', 'footer_menu_1');


if ($footerMenu1->isNotEmpty()) {

$menuItems = $footerMenu1->menuItems()->toPages();
    
if ($menuItems->isNotEmpty()) { ?>
            <nav class="footer-menu">
                <h4><?= $footerMenu1->menuHeadline()->html() ?></h4>
                <ul>
                    <?php foreach ($menuItems as $menuItem) : ?>
                        <li><a href="<?= $menuItem->url() ?>"><?= $menuItem->title() ?></a></li>
                    <?php endforeach ?>
                </ul>
            </nav>
    <?php
}
}

Note that this if statement will throw an error if $footerMenu1 is null (the item doesn’t exist) therefore use the if statement I posted above.