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.

9 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!

Feb 10 2012 07:28

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

Jun 13 2012 14:39

Brilliant, many thanks for posting this.

Apr 02 2013 02:16

Just what I needed!!!

Apr 25 2013 17:19

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

Apr 30 2013 22:25

Thanks so much for this!

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox