Adding ACF fields to menu item to the nav walker

Hello!

I’m trying to add an image to a menu item (client wants an image full width in the dropdown, below the menu items), and the code i’m getting from ACF is failing, and i’m not sure why…

I am pasting this in my filters.php

add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);

function my_wp_nav_menu_objects( $items, $args ) {
	
	// loop
	foreach( $items as &$item ) {
		
		// vars
		$image = get_field('menu_image', $item);
		
		
		// append icon
		if( $image ) {
			
			$item .= ' <img src="' . $image . '" />';
			
		}
		
	}
	
	
	// return
	return $items;
	
}   

and i’m getting this error:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘my_wp_nav_menu_objects’ not found or invalid function name in …/wp-includes/class-wp-hook.php on line 286

This is the snippet taken directly from ACF, so i’m not sure why it’s not working…

Thanks in advance for your help everyone,

Ty

filters.php is in the App namespace. Your error message is telling you that it cannot find the callback:

‘my_wp_nav_menu_objects’ not found or invalid function name

This should be your first clue as to what the problem is.

When callbacks to filters and actions are called, they are not called in the context in which they are defined. In other words, although you have defined my_wp_nav_menu_objects() in the App namespace by putting it in filters.php, when it is called by do_filter later on, it is just called as my_wp_nav_menu_objects, which does not exist: the fully-qualified function name is App\my_wp_nav_menu_objects(). To handle this, whenever defining filter or action callbacks in namespaced files, you should add the namespace to the callback string like so:

add_filter('wp_nav_menu_objects', __NAMESPACE__.'\\my_wp_nav_menu_objects', 10, 2);

Alternatively, you can also just pass anonymous functions instead of callback strings:

add_filter('wp_nav_menu_objects', function( $items, $args ) {
	
	// loop
	foreach( $items as &$item ) {
		
		// vars
		$image = get_field('menu_image', $item);
		
		
		// append icon
		if( $image ) {
			
			$item .= ' <img src="' . $image . '" />';
			
		}
		
	}
	
	
	// return
	return $items;
	
}, 10, 2);
1 Like