Add Image within Nav Item Link

The outcome of this snippet will be an image with the size “square” (assuming you have this in your functions.php) followed by the nav item title. This is also assuming you have attached a custom image field using ACF with the name of associated_item_image.

// Add image within menu item link.
add_filter('wp_nav_menu_objects', 'prefix_wp_nav_menu_objects', 10, 2);
function prefix_wp_nav_menu_objects( $items, $args ) {
	foreach( $items as $item ) {
		$associated_img = get_field( 'associated_item_image', $item );

		if( $associated_img ) {
			$item->title = $item->title . '<img class="associated-img" src="' . $associated_img['sizes']['square'] . '" alt="' . $associated_img['alt'] . '" /> ';
		}
	}
	return $items;
}

Leave a Reply

Your email address will not be published. Required fields are marked *