0

Trying to pull through the featured image in a custom menu without a plugin so I can style it how I want.

This is the code I have so far;

<?php
$navMenu = wp_get_nav_menu_items(6); /*/Pass Nav Menu_id or Name*/
$previousMenuParent = $level = 0;                         
foreach ($navMenu as $menu) {
    $level = 0;
    echo '<li style="background-image:url("");"><a href="'. $menu->url .'">'. $menu->title .'</a>';                            
    echo '<br><br>';
    echo $menu->title = has_post_thumbnail($menu->object_id) ? get_the_post_thumbnail($menu->object_id, 'thumbnail') : $menu->title;
}
?>

I've also tried;

echo get_the_post_thumbnail($menu->ID);

I feel I'm so close but either get errors or nothing (or in the latest case just the title again)

Can anyone help get me over the line please?

  • I'm not sure about the HTML or CSS but the PHP code should work. menu->object_id holds the assigned Post ID and has_post_thumbnail( $menu->object_id ) should return whether or not that page/post has an uploaded featured image. – Howdy_McGee Oct 26 '17 at 15:43
  • I did echo has_post_thumbnail( $menu->object_id ); and nothing happened – Sam Oct 27 '17 at 8:21
  • Then you need to debug your code and figure out if $menu has a property of object_id and if $menu->object_id is the expected post ID. If not you need to print the entire $navMenu variable to ensure it holds what you expect. This code should be right which means there's something else wrong up the line. – Howdy_McGee Oct 27 '17 at 14:26
  • Thanks for the continued help, I did print_r and got a lot back, it has object_id – Sam Oct 30 '17 at 9:18
  • Check and see if the printed object_id is the same as what you expected the Post ID for that assigned item to be. If they're the same then your above code should work and we would need more information on where, when, and how it's being run. Is this inside a function? header.php? First thing's first, ensure your object_id is the same as the Post ID – Howdy_McGee Oct 30 '17 at 14:14
0
<?php
    $navMenu = wp_get_nav_menu_items(6);                                                    
    foreach ($navMenu as $menu) {                            
        echo '<li style="background-image:url( '. get_the_post_thumbnail_url( $menu->object_id ) .' )">';
        echo '<a href="'. $menu->url .'">'. $menu->title .'</a>';
    }
?>

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.