0

I have the following page hierarchy:

  • Page Grandparent (This page)
    • Page Parent 1 (Should direct here)
    • Page Parent 2
      • Page Child
      • Page Child
    • Page Parent 3
    • Page Parent 4

My parent and child pages have been assigned via page attributes. The pages are then ordered via Appearance > Menus.

On the front end, when you click on Page Grandparent, I'd like it to redirect to the next menu item (Page Parent 1).

To achieve this, I've built the following page template and applied it to my Page Grandparent.

<?php
/**
 * Template Name: Redirect to next menu item
 */
  if (have_posts()) {
  while (have_posts()) {
      the_post();
      $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order");
      $firstchild = $pagekids[0];
      wp_redirect(get_permalink($firstchild->ID));
      exit;
    }
  }
 ?>

For some reason, the page is directing to Page Parent 2. What am I doing wrong here?

  • I think you're getting tripped up by menu_order. The Codex says that for get_pages(), menu_order sorts by Page Order, which is a number you enter on the Page editing screen itself and actually has nothing to do with Menus. So, if you edit Page Parent 1 and give it a Page Order, that should fix the problem. Or, more extensible and less manual, have it always alphabetize by title and use orderby title rather than menu_order. – WebElaine Oct 11 '18 at 15:18
  • That makes sense. Problem is, the client wants to order via Appearance > Menus not using the order field. Can the re-direct work this way? – Sam Oct 11 '18 at 15:33
  • 1
    I don't think there's a reliable way to identify by that method. For one thing there could be multiple menus that contain the pages, so you wouldn't know which to use, or how it relates to any of the other items - the other links in the menu may not correspond to the hierarchy since menus are created manually. It is probably best to train the client to use Page Order, so they still retain control of the order everywhere, and then instead of a Menu, use wp_list_pages() or something similar, using that same Page Order. You can then rely on redirecting to the 2nd item in the list. – WebElaine Oct 11 '18 at 17:54
  • Thank you @WebElaine. I'll use the method you've suggested. – Sam Oct 11 '18 at 20:02
0

As @WebElaine said, menu_order sorts by Page Order.

So, you have to update your pages and set the order manually.

enter image description here

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.