functions – How to display an image before title text in menu items


I am using Advanced Custom Fields to add images to individual menu items. These images are being appended to the $item->title with the following code:

function wp3456789_wp_nav_menu_objects( $items, $args ) {
  foreach( $items as &$item ) {
    $image = get_field('icon', $item);
    if( $image ) {
      $item->title .= '<span class="inline-img' . $item->class . '"><img class="style-svg" src="' . $image['url'] . '" width="" height="" alt="' . $image['alt'] . '" /></span>';
  return $items; 
add_filter('wp_nav_menu_objects', 'wp3456789_wp_nav_menu_objects', 10, 2);

Instead of appending the images, I am needing to have the <span> and replaced images display before the $item->title text.

The images are being replaced using the SVG Support plugin with the style-svg class.

For example:

<a href="#">
  <span class="inline-img">
    <svg role="img" xmlns="" viewBox="0 0 576 512">
      <!-- SVG image -->
  Menu Item Title

The wp_nav_menu code for rendering the menu:

$args = array(
  'theme_location' => 'global-footer-navigation',
  'menu_id' => 'global-footer-navigation',
  'container' => false,
  'echo' => false,
  'items_wrap' => '%3$s',
  'depth' => 0,
// Strip all remaining menu HTML except for <a>, <span>, and <img> tags
echo strip_tags(wp_nav_menu( $args ), '<a><span><img>' );

How can I filter the menu item title text and have the <span> display before it?

Mike Hermary 2 years 2021-11-23T09:41:43-05:00 0 Answers 0 views 0

Leave an answer