Walker_Nav_Menu: put custom code between a particular

You need to make your own walker menu (i am guessing you already know that), and the best way i think is overriding the function that ends each menu item which is end_el :

class logo_in_middle_Menu_Walker extends Walker_Nav_Menu {

    public $menu_location = 'primary';

    function __construct($menu_location_var) {
        // parent class doesnt have a constructor so no parent::__construct();
        $this->menu_location = $menu_location_var;
    }

    public function end_el(&$output, $item, $depth = 0, $args = array()) {
        $locations = get_nav_menu_locations(); //get all menu locations
        $menu = wp_get_nav_menu_object($locations[$this->menu_location]); //one menu for one location so lets get the menu of this location
        $menu_items = wp_get_nav_menu_items($menu->term_id);

        $top_lvl_menu_items_count = 0; //we need this to work with a menu with children too so we dont use simply $menu->count here
        foreach ($menu_items as $menu_item) {
            if ($menu_item->menu_item_parent == "0") {
                $top_lvl_menu_items_count++;
            }
        }

        $total_menu_items = $top_lvl_menu_items_count;

        $item_position = $item->menu_order;

        $position_to_have_the_logo = ceil($total_menu_items / 2);

        if ($item_position == $position_to_have_the_logo && $item->menu_item_parent == "0") { //make sure we output for top level only
            $output .= "</li>\n<img src="https://wordpress.stackexchange.com/questions/256868/PATH_TO_YOUR_LOGO" alt="" />"; //here we add the logo
        } else {
            $output .= "</li>\n";
        }
    }
}

i am assuming that if its a menu with an uneven number of item say 5 the logo will be after the third element, also that this is only for top elements only.

you have to use it like this in the menu location:

<?php
    wp_nav_menu(array(
            'theme_location' => 'footer',
            "walker" => new logo_in_middle_Menu_Walker('footer'),
    ));
?>

you have to supply the name of the theme location.

Here with 4 items:

enter image description here

Here with 5:

enter image description here

Leave a Comment