0

I am calling a menu into a page, but I want to add images next to the title of the menu items.

I have this code:

<ol>
<?php
    $navMenu = wp_get_nav_menu_items(2096); /*/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 .'"><img src="'. get_the_post_thumbnail($menu->ID) .'"/> '. $menu->title .'</a>';
            
        }
      
    }
?>
</li>

It works, it is showing the list of the menu items, with title and link, but for some reason, it won't show the post's image next to its title.

I also tried using get_the_post_thumbnail('thumbnail') instead of get_the_post_thumbnail($menu->ID) but that won't show an image either, with or without the <img src="

I would also prefer to call a post's custom field, which has an image URL, instead of the post thumbnail. Is that possible?

Any help would be greatly appreciated.

Thank you

1 Answer 1

1

I guess you need this function

get_the_post_thumbnail_url($menu->object_id);

(provided menu item is not a custom link)

$menu->ID is not the id of the post/page it is linking to.

About calling meta yes it is also possible

$image_url = get_post_meta( $menu->object_id, 'meta_key', true );
2
  • many thanks! this works. I simply used get_post_meta ($menu->object_id, 'meta_key', true ) inside my code and did the trick. and I removed one bracket from your code, maybe a typo
    – vyperlook
    Apr 22 at 16:29
  • 1
    Welcome, and yes there was a typo. I have updated the answer.
    – MMK
    Apr 26 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.