how to set feature image inside nav menu

Posted: July 17, 2015 in Uncategorized
Tags: , , , ,

To do that ,first we need to check what is inside menu item?whether it brings taxonomy or post .and if it contains post then get feature image.for that we need to add filter called ‘wp_nav_menu_args’

Add filter to specific menus

add_filter(‘wp_nav_menu_args’, ‘add_filter_to_menus’);
function add_filter_to_menus($args) {

// You can test agasint things like $args[‘menu’], $args[‘menu_id’] or $args[‘theme_location’]
if( $args[‘theme_location’] == ‘header_menu’) {
add_filter( ‘wp_setup_nav_menu_item’, ‘filter_menu_items’ );

Filter menu

function filter_menu_items($item)

if ($item->type == ‘taxonomy’) {

// For category menu items
$cat_base = get_option(‘category_base’);
if (empty($cat_base)) {
$cat_base = ‘category’;

// Get the path to the category (excluding the home and category base parts of the URL)
$cat_path = str_replace(home_url() . ‘/’ . $cat_base, ”, $item->url);

// Get category and image ID
$cat = get_category_by_path($cat_path, true);
$thumb_id = get_term_meta($cat->term_id, ‘_term_image_id’, true); // I’m using the ‘Simple Term Meta’ plugin to store an attachment ID as the featured image

} else {
// Get post and image ID
$post_id = url_to_postid($item->url);
$thumb_id = get_post_thumbnail_id($post_id);

if (!empty($thumb_id)) {
// Make the title just be the featured image.
$item->title = wp_get_attachment_image($thumb_id, ‘poster’);

return $item;

And then you want to remove the filter that you applied at the beginning, so that the next menu processed doesn’t use the same HTML as defined above in filter_menu_items().
Remove filters

add_filter(‘wp_nav_menu_items’,’remove_filter_from_menus’, 10, 2);
function remove_filter_from_menus( $nav, $args ) {
remove_filter( ‘wp_setup_nav_menu_item’, ‘filter_menu_items’ );
return $nav;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s