显示带有子菜单和缩略图的 wordpress 菜单 [英] Displaying a wordpress menu with submenu and thumbnail

查看:41
本文介绍了显示带有子菜单和缩略图的 wordpress 菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整个上午都被困在这个问题上,我不认为我能走得更远.

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

我想显示一个 wordpress 菜单,然后我想显示父菜单的所有子页面,所有子页面都有缩略图,我希望这些显示出来.

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.

我正在尝试将缩略图添加到子页面的 ing 标签中

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

这是我查看代码的方式

父菜单

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

子菜单

<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>

谢谢

推荐答案

在我这边测试得到了令人满意的结果.这将影响所有菜单,因此请随意添加其他逻辑以仅针对某些菜单.

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.

您可能需要对其进行样式设置以使其看起来更好一些,但只需将其放入您的functions.php 文件中即可:

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;
}

这篇关于显示带有子菜单和缩略图的 wordpress 菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆