Forums

[resolved] If page has subpages - redirect to first child, else - stay on current page (5 posts)

  1. pete.kyle
    Member
    Posted 9 months ago #

    Hi everyone,

    I am trying to create a new page template so that if the page has subpages, it will automatically be redirected to the first one, and if it doesn't have any subpages it should display the current page.

    I got this code from another forum:

    <?php
    /*
    Template Name: Redirect To First Child
    */
    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));
      }
    }
    ?>

    I have tried to alter the code to remain on the current page if there are no children but I cannot stop it going in an infinite redirect loop.

    Any suggestions?

    Thanks a million,

    Pete

  2. MichaelH
    moderator
    Posted 9 months ago #

    Would if statement do it:

    $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order");
    if ($pagekids) {
    $firstchild = $pagekids[0];
    wp_redirect(get_permalink($firstchild->ID));
    }
  3. pete.kyle
    Member
    Posted 9 months ago #

    that's brilliant thanks!!!

  4. aalaap
    Member
    Posted 9 months ago #

    What would be the best way to incorporate conditional redirection?

    For example, if I have a Products page with four sub-pages for each product, I don't want it to go to Product 1 automatically; I want it to stay on the Products page which has a introductory write-up. At the same time, however, I may have an About Us page which has four sub-pages, but I want the first sub-page to be displayed when the About Us page is visited.

    I'd suggest using a custom field called "dont_redirect" which can be set to 0 or 1. It will default to 0 (false), which means if this isn't specifically set to 1, it will always redirect to the children.

    Here is the entire code block modified:

    if (have_posts()) {
      while (have_posts()) {
        the_post();
        $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order");
        if ($pagekids) {
          if (!get_post_meta($post->ID, 'dont_redirect', true)) {
            $firstchild = $pagekids[0];
            wp_redirect(get_permalink($firstchild->ID));
          }
        }
      }
    }

    Now I just set a 'dont_redirect' custom field in my Products page, set it to 1 and the page stays right there!

    Thanks to wildpawtrax for the original code and MichaelH for the infinite loop fix.

  5. iDRez
    Member
    Posted 8 months ago #

    What about altering the wp_list_pages?

    I started a thread...

    http://wordpress.org/support/topic/249009?replies=2

Reply

You must log in to post.

About this Topic