In this article, I will show you how you can add a featured image to a dropdown menu. To give you an idea of what we will be creating, you can have a look at the below website:
For this website, we used the featured images to showcase the products within the menu. So how do we achieve this?
Basically, what we did was add a class within our menu to target the menu in which we wanted to add the featured image too, that class we used was swd-special-dropdown
.
We added this code to the parent menu item (Products), which will then apply the featured image to each child once we add the code needed within your functions.php
file.
So the first step you will need to do is go to Appearance
β Menus
. You will need to click CSS Classes
, this will allow you to add a class to any of the menu items.
Now, simply add the class swd-special-dropdown
to your desired menu item, in our case, we added this to Products.
Once this part is completed, the next step is to add some code to your functions.php
file. What the below code does is check if any main link in the navigation contains the class swd-special-dropdown
. If it does, it will loop through all the sub-items and will show a featured image next to the navigation label.
/**
* Add the images to the special submenu -> the submenu items with the parent with 'swd-special-dropdown' class.
*
*/
function add_images_to_special_submenu( $items ) {
$special_menu_parent_ids = array();
foreach ( $items as $item ) {
if ( in_array( 'swd-special-dropdown', $item->classes, true ) && isset( $item->ID ) ) {
$special_menu_parent_ids[] = $item->ID;
}
if ( in_array( $item->menu_item_parent, $special_menu_parent_ids ) && has_post_thumbnail( $item->object_id ) ) {
$item->title = sprintf(
'%1$s %2$s',
get_the_post_thumbnail( $item->object_id, 'full', array( 'alt' => esc_attr( $item->title ) ) ),
$item->title
);
}
}
return $items;
}
add_filter( 'wp_nav_menu_objects', 'add_images_to_special_submenu' );
And that’s essentially it!
Obviously, it will require some CSS work to give it the look you desire, but that’s essentially all there is to it!
If you prefer to not do any custom coding, there are several Plugins you can download to achieve the same result such as Max Mega Menu.
Let me know in the comments if you’ve used this code on one of your websites, and if you have any questions, simply get in touch.
A webinar is an online event that is hosted by an organisation or company and broadcast to a selected group of individuals through their computers on the Internet. This can also be referred to as a ‘webcast’, an ‘online event’ or ‘web seminar’). Webinar Care is a perfect solution for for how you can make webinars work amazingly for you, I’d definitely check them out.
Wonderful solutions, thanks.