Show submenu for a particular parent level item in

2019-08-24 19:04发布

问题:

I have a main menu on a wordpress site using wp_nav_menu that goes as 4 parent items, and each have a few sub menu items.

On particular template, I would like to show the submenu items for one of the parent items. For instance:

  • Parent Item 1
    • List Item 1
    • List Item 2
  • Parent Item 2
    • List Item 1
    • List Item 2
  • Parent Item 3
    • List Item 1
    • List Item 2
  • Parent Item 4
    • List Item 1
    • List Item 2

In my template I would like to show List Item 1 and List Item 2 for Parent Item 3. Each parent item has a unique ID. On 'pages' I use the following code to accomplish it:

            <?php
            if($post->post_parent)
                $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
            else
                $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
            if ($children) { ?>
                 <ul id="side-page-menu">
                    <?php echo $children; ?>
                </ul>
        <?php } ?>

But that does not appear to work for single posts (compared to pages).

Thanks!

回答1:

Tried with this

<ul>
            <?php wp_list_pages('title_li=<h2>MAIN NAV</h2>&depth=1' ); ?>
            </ul>
            <?php
                if ($post->post_parent == 0) {
                $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
                $parentpage = $wpdb->get_row("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE ID = '".$post->ID."'");
                }
                if ($post->post_parent != 0) {
                $next_post_parent = $post->post_parent;
                while ($next_post_parent != 0) {
                $children = wp_list_pages("title_li=&child_of=".$next_post_parent."&echo=0");
                $parentpage = $wpdb->get_row("SELECT ID, post_title, post_parent, post_name FROM $wpdb->posts WHERE ID = '".$next_post_parent."'");
                $next_post_parent = $parentpage->post_parent;
                }
            }
            ?>
            <?php if ($children) { ?>
            <ul>
                <li>SUBNAV FOR: <a href="<?php echo get_permalink($parentpage->ID); ?>"><?php echo $parentpage->post_title; ?></a>
            <ul>
            <?php echo $children; ?>
            </ul>
            </li>
            </ul>
            <?php } ?>


标签: wordpress