TransWikia.com

Add Featured Image and Title to wp_nav_menu items

WordPress Development Asked by red5 on November 19, 2020

I like this solution from Ahmad M, a lot, but how do I add images in addition to titles, instead of replacing titles? (Sorry, I’m still pretty new to PHP and Stackexchange).

Pulling Featured Images in to a WordPress Menu

I mostly figured it out. I’m using Ahmad M’s filter but needed to add “.$menu_object->title” to the thumbnail so now it looks like:

$menu_object->title = has_post_thumbnail($menu_object->object_id) ? get_the_post_thumbnail($menu_object->object_id, 'full') .  $menu_object->title .  : $menu_object->title;

Now my challenge is that I only want to add it to third level menu items (child of a child of a parent).

One Answer

The following code will get you the featured image for 3rd level of your navbar. You, have to pass the nav-menu id within wp_get_nav_menu_items(). It will get you the menu list (For more details).

<ul>
    <?php
        $navMenu = wp_get_nav_menu_items(9); /*/Pass Nav Menu_id or Name*/
        $previousMenuParent = $level = 0;
        foreach ($navMenu as $menu) {

            if($menu->menu_item_parent == 0)
            {
                $level = 0;
                echo '<li><a href="'. $menu->url .'">'. $menu->title .'</a>';
            }
            elseif($menu->menu_item_parent != '' && $menu->menu_item_parent != $previousMenuParent)
            {
                $level++;
                echo '<ul class="submenu">';
                echo '<li><a href="'. $menu->url .'">'. $menu->title .'</a>';
                $previousMenuParent = $menu->menu_item_parent;
            }
            elseif($previousMenuParent == $menu->menu_item_parent)
            {
                echo '</li><li><a href="'. $menu->url .'">';
                if($level == 3)
                {
                    echo get_the_post_thumbnail($menu->ID);
                }
                echo $menu->title .'</a>';
            }
        }
    ?>
    </li>
</ul>

Answered by BlueSuiter on November 19, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP