0

I am looking to create a menu that displays the child pages when on a parent page, but to then show the siblings when on any of the sibling's pages?

-Car
--VW
--Ford
--BMW
-Bike
-Motobike

So when on the Car page the output would be the following links:
Car, VW, Ford, BMW
and when on the Ford page the output would be the following links:
Car, VW, Ford, BMW

I have found some similar examples with the best one being https://learnwebcode.com/wordpress-child-page-menu-parent-and-subpages/ but this does not show an active menu item and also does not work for a custom post type.

        <?php

        if ( has_children() OR $post->post_parent > 0 ) { ?>

            <nav class="site-nav children-links clearfix">

                <span class="parent-link"><a href="<?php echo get_the_permalink(get_top_ancestor_id()); ?>"><?php echo get_the_title(get_top_ancestor_id()); ?></a></span>

                <ul>
                    <?php

                    $args = array(
                        'child_of' => get_top_ancestor_id(),
                        'title_li' => ''
                    );

                    ?>

                    <?php wp_list_pages($args); ?>
                </ul>
            </nav>

        <?php } ?>

I am surprised there is not already an existing solution for this.

How do I create a menu from a custom post type that indicates the current page and shows the children if it a parent page and if it is a child page, it show the children from the same parent and the parent?

1

1 Answer 1

0

OK, I think I have cracked it. The below code seems to work well. To be able to use a custom post type I added an argument into the $args array'post_type' => 'product',

Is the below OK?

      <div id="sub-pages">
        <?php
        global $post;
        $args = array(
          'post_type' => 'product',
          'child_of' => get_top_ancestor_id(),
          'title_li' => ''
        );
        $the_query = new WP_Query($args);
        ?>
        <ul>
          <?php wp_list_pages($args); ?>
        </ul>
        <?php wp_reset_postdata(); ?>
      </div>
// Get top ancestor
function get_top_ancestor_id() {

    global $post;

    if ($post->post_parent) {
        $ancestors = array_reverse(get_post_ancestors($post->ID));
        return $ancestors[0];
    }

    return $post->ID;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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