Search code examples
wordpressadvanced-custom-fields

Get custom field ACF in custom menu


I have a menu in Wordpress with an ACF field called "svg"

To create my menu, I do this:

function b_get_menu_id( $location )
{
  $a = get_nav_menu_locations();
  if (isset($a[$location])) return $a[$location];
  return false;
}

function b_get_nav_items($location) {
  $id = b_get_menu_id($location);
  $nav = [];
  $children = [];
  if(!$id) {
    return $nav;
  }
  foreach(wp_get_nav_menu_items($id) as $object) {
    $item = new stdClass();
    $item->url = $object->url;
    $item->label = $object->title;
    $item->id = $object->object_id;
    $item->icon = $object->classes[0];
    $item->parent = intval($object->menu_item_parent);
    $item->children = [];
    if($item->parent){
      $children[] = $item;
    } else {
      $nav[$object->ID] = $item;
    }
  }
  foreach($children as $item) {
    $nav[$item->parent]->children[] = $item;
  }
  return $nav;
}

I display my menu like this:

@foreach(b_get_nav_items('primary_navigation') as $item)
... my html here...
@endforeach

In my foreach, I'm trying to call my ACF fields from my menu like this:

<?php get_field('svg', $item->id)

But it does not work (null). I'm lost. How can I get my ACF field?

thank you so much


Solution

  • It's not documented in the ACF docs, but this seems to work if you prefix with "menu_". For example:

    get_field('field_name', 'menu_' . $menu_id);