I’ve got a simple static list marked up like this that I’d like to turn in to a WordPress Menu:
<ul>
<li><a href="#"><img src="https://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="https://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="https://placekitten.com/200/300"></a></li>
<li><a href="#"><img src="https://placekitten.com/200/300"></a></li>
</ul>
I’d like each list item to link to a specific post, and pull in the Featured Image rather than the title. If I setup a default WordPress Menu it would output like this:
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/87017/post-1/">Blog Post 1</a></li>
<li><a href="post-2/">Blog Post 2</a></li>
<li><a href="post-3/">Blog Post 3</a></li>
<li><a href="post-4/">Blog Post 4</a></li>
</ul>
How would I instead output it like this:
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/87017/post-1/"><img src="post-1-featured-img.png"></a></li>
<li><a href="post-2/"><img src="post-2-featured-img.png"></a></li>
<li><a href="post-3/"><img src="post-3-featured-img.png"></a></li>
<li><a href="post-4/"><img src="post-4-featured-img.png"></a></li>
</ul>
So essentially I’d just like to return the Featured Image of each post I specify in a WordPress Custom Menu rather than the post title.
You can do that by filtering the menu objects using wp_nav_menu_objects
filter.
The following example will replace all titles of the menu items pointing to posts or pages with an <img>
tag of the post or page thumbnail if available. It will target a menu with a name of Posts Menu
called in theme using wp_nav_menu(array('menu'=>'Posts Menu'))
:
add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2);
function ad_filter_menu($sorted_menu_objects, $args) {
// check for the right menu to filter
// here we check for the menu with name 'Posts Menu'
// given that you call it in you theme with:
// wp_nav_menu( array( 'menu' => 'Posts Menu' ) );
// if you call the menu using theme_location, eg:
// wp_nav_menu( array( 'theme_location' => 'top_manu' ) );
// check for:
// if ($args->theme_location != 'top_menu')
if ($args->menu != 'Posts Menu')
return $sorted_menu_objects;
// edit the menu objects
foreach ($sorted_menu_objects as $menu_object) {
// searching for menu items linking to posts or pages
// can add as many post types to the array
if ( in_array($menu_object->object, array('post', 'page', 'any_post_type')) ) {
// set the title to the post_thumbnail if available
// thumbnail size is the second parameter of get_the_post_thumbnail()
$menu_object->title = has_post_thumbnail($menu_object->object_id) ? get_the_post_thumbnail($menu_object->object_id, 'thumbnail') : $menu_object->title;
}
}
return $sorted_menu_objects;
}