WordPress – 301 location to sub page

WordPress is great for blogging but still has a way to go to be a CMS. One thing I find odd is that you can create Categories for Posts but not for Pages. Usually a client will want pages categorized for navigation. So this becomes a problem. Sure you can nest Pages (parents and children) but that means you must have content in every menu item.

After a quick google search I came across some code that allows WP’s Pages to have empty menu items for categorization. Or at least that’s the visual effect. The fix is to create a Template in your theme with some PHP code. It redirects the browser to the first Child Page:

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

This works but I’m not too fond of it. It uses a refresh. I tweaked it a bit. Changed the wp_redirect to a Location header and added a 301 status code:

<?php
/*
Template Name: 301 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];
  header("HTTP/1.1 301 Moved Permanently");
  header("Location: ".get_permalink($firstchild->ID));
  exit();
 }
}
?>

This is much faster on the front end. It also tells search engines not to index those blank categorization pages.

<?php/*Template Name: 301 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];   header(“HTTP/1.1 301 Moved Permanently”);   header(“Location: “.get_permalink($firstchild->ID));   exit();  }}?>