Displaying a wordpress menu with submenu and thumb

2019-08-30 08:09发布

I've been stuck on this all morning and I don't think i'm that much further.

I'm trying to display a wordpress menu, I then want to display all the child pages for the parent menu, all the child pages have thumbnails and I want these to show to.

I'me trying to add the thumbnails into the ing tag in the child pages

Here's how I went the code to look

Parent menu

<nav>
  <a href="#" >Sample Page 1</a>
  <a href="#" >Sample Page 2</a>
</nav>

Child menu

<ul class="sample_page_1">
  <li>
    <a href="#">
      <img src="image.jpg" alt="img05">
      <h4>Belts</h4>
    </a>
  </li>
  <li>
    <a href="#">
      <img src="image.jpg" alt="img05">
      <h4>Belts</h4>
    </a>
  </li>
</ul>

<ul class="sample_page_2">
  <li>
    <a href="#">
      <img src="image.jpg" alt="img05">
      <h4>Belts</h4>
    </a>
  </li>
  <li>
    <a href="#">
      <img src="image.jpg" alt="img05">
      <h4>Belts</h4>
    </a>
  </li>
</ul>

Here's the code I have so far but it's not doing what it should, it's not displaying the images and I can't figure out how? Not even sure it's it the correct way to do it?

<ul>
<?php
$menu_name = 'shoes';
    $items = wp_get_nav_menu_items($menu_name);
    foreach ( $items as $item){
        echo '<li><a href="#">'.$item->title.'</a></li>';
    }
?>
</ul>

Thanks

1条回答
三岁会撩人
2楼-- · 2019-08-30 09:05

Testing this on my end yielded satisfactory results. This will affect ALL menus, so feel free to add additional logic to only target certain menus.

You'll probably have to style it to make it look a bit better, but just drop this into your functions.php file:

add_filter('walker_nav_menu_start_el', 'maiorano_generate_nav_images', 20, 4);
function maiorano_generate_nav_images($item_output, $item, $depth, $args){
    if(has_post_thumbnail($item->object_id)){
        $dom = new DOMDocument(); //DOM Parser because RegEx is a terrible idea
        $dom->loadHTML($item_output); //Load the markup provided by the original walker
        $img = $dom->createDocumentFragment(); //Create arbitrary Element
        $img->appendXML(get_the_post_thumbnail($item->object_id, 'thumbnail')); //Apply image data via string
        $dom->getElementsByTagName('a')->item(0)->appendChild($img); //Append the image to the link
        $item_output = $dom->saveHTML(); //Replace the original output
    }
    return $item_output;
}
查看更多
登录 后发表回答