Post Pic

WordPress page template to redirect to first child page

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.

Related Posts

Related Posts

No related posts.

4 Responses

Aug 19 2011 13:50

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

Nov 09 2011 00:08

Great recipe! Short and sweet.

Thanks for sharing!

Dec 02 2011 21:51

Thanks for sharing!
Saved my job :)

Jan 07 2012 23:55

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

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required