2

I'm trying to add an image to menu item, can't get it to work.

Here is my code. header.php

<?php wp_nav_menu(
                    array(
                        'theme_location'  => 'side-menu',
                        'container_class' => 'fixed-menu',
                        'fallback_cb'     => '',
                        'link_before'     => '<span>',
                        'lnk_after'       => '</span>',
                        'depth'           => 2,
                        'walker'          => new Understrap_WP_Bootstrap_Navwalker(),
                    )
                ); ?>

And here is the function.php

// Header Side Menu
function etm_side_menu() {
  register_nav_menu('side-menu',__( 'Header Side Menu' ));
}
add_action( 'init', 'etm_side_menu' );


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

function wp_nav_menu_objects( $items, $args ) {

    // loop
    foreach( $items as &$item ) {

        // vars
        $icon = get_field('icon'); 


        // append icon
        if( $icon ) {

            $item->title .= '<img src='.$icon.'>';

        }

    }


    // return
    return $items;

}

The images that suppose to appear in the menu, just don't come on. Any help will be appreciated.

I am using understrap theme.

The desired markup is this

<div class="fixed-menu">
        <ul>
            <li class="active">
               <a href="#">
                  <img src="img/fx-ic-1.png" alt="img">
                  <span>Главная</span>
               </a>
             </li>
             etc...
3
  • Unless your theme has added a hook, you need to use add_filter('wp_nav_menu_objects'... instead of add_filter('my_wp_nav_menu_objects'. wp_nav_menu_objects is the Core hook.
    – WebElaine
    Commented Oct 3, 2019 at 15:54
  • Thanks for your answer, but to no avail, to icons are not populated. Commented Oct 3, 2019 at 21:25
  • You also need to update your get_field() call and pass in the post ID. Otherwise ACF can't get the data. It wouldn't hurt to simplify your code as you are testing to first add a <span> or something to every item, to verify you're using the right hooks, and then move on to the conditional part. Breaking it down into smaller steps helps identify which step is currently causing an issue.
    – WebElaine
    Commented Oct 3, 2019 at 21:37

1 Answer 1

0

get_field() gets the field for the current post in the loop, but the loop isn't used for menu items, so you need to specify which post you want to get the value from. In the case of menu items, each nav menu item is a WP_Post object, so you want to pass that:

foreach( $items as &$item ) {
    $icon = get_field( 'icon', $item );
    // etc.
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.