DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

Many WordPress users uses parent pages and subpages to order the informations displayed on their blogs. A heavily requested recipe is how to be able to redirect to the first child page if the current page have children pages? here is the answer.

To achieve this recipe, you have to create a page template. Create a new file and paste the following code in it:

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

Save the file under the name redirect.php and upload it to the wp-content/themes/your-theme directory of your WordPress install. Once done, you can use the page template.
If you don’t know how to use page templates, refer to this recipe.

10 Comments

  1. Fabricio Bisso

    Fantastic! just right what I was looking for, many thanks!!

  2. Great recipe! Short and sweet.

    Thanks for sharing!

  3. Thanks for sharing!
    Saved my job 🙂

  4. Just what I needed – I had a gallery page that displayed sub-pages, but wanted to default to the top sub-page. Anyhow, thanks!

  5. I want subpage title first and follow as page title

    eg: consider google is an site name and it have pages and subpages

    now i want, when i click the pages then it shows Google – page in the main title. suppose if i click the subpages from the pges then it shows like subpage – Google.

    i done first one that is Google – page. i dont know that how to get subpage – Google. pls suggestion some solutions as soon as possible

  6. Brilliant, many thanks for posting this.

  7. Just what I needed!!!

  8. wp_redirect() does not exit automatically and should almost always be followed by exit.

  9. Thanks so much for this!

  10. Thank you!
    Simple and ingenious 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *