jmccole83
8/27/2019 - 3:16 PM

WordPress | Get all menus on site, add to select field.

// Get registered menus, populate select field
function acf_load_menu_field_choices( $field ) {
// reset choices
$field['choices'] = array();
$menus = get_terms( 'nav_menu', array( 'hide_empty' => false ) );
//$menus = get_registered_nav_menus(); //uncomment this if you want to populate the dropdown with all Menu Locations
$blank_list = json_encode(array( "name" => "Primary Navigation", "term_id" => ""));
$blank_list = json_decode($blank_list);
array_unshift($menus, $blank_list);

foreach ( $menus as $val ) {
  $value = $val->term_id;
  $label = $val->name;
  $field['choices'][ $value ] = $label;
}

// return the field
return $field;

}
add_filter('acf/load_field/name=menu_select', __NAMESPACE__ . '\\acf_load_menu_field_choices'); //replace custom_menu with your field name
// Menu Select
public function menu_select()
{
  $menu = get_field('menu_select');

  if(!empty($menu)) {
    $menu = strtolower( str_replace(' ', '-', $menu['label']) );
  }

  return $menu;
}
@if (!empty($menu_select))
<div class="w-100 secondary-nav {!! $mobile_breakpoint !!}">
  <div class="container px-5">
    <nav>
      {!! wp_nav_menu([
        'menu'              => $menu_select,
        'depth'             => 2,
        'container'         => 'div',
        'container_class'   => 'navbar-collapse',
        'container_id'      => 'bs-example-navbar-collapse-1',
        'menu_class'        => 'position-relative m-0 px-0 py-3 list-unstyled d-flex',
      ]) !!}
    </nav>
  </div>
</div>
@endif