I’ve been redesigning the website for a web application I am writing. The site uses WordPress because I wanted a blog section and wanted visitors to be able to easily leave comments on any page. So the entire site is backed with WordPress with most of the content on pages rather than posts.
One of the sections is documentation and it’s broken down with child, grandchild, and so on pages. So I might have a page /customization/themes/. /customization/ isn’t really a page to look at, but needs to be there to act as a container for its children and will therefore show up in the XML sitemap which means it’ll get indexed by the search engines. Don’t really want that.
My first instinct was to just print a list of the child pages so the visitor could click on one of them. A little clunky, but it would’ve worked.
Found a better solution at WPRecipes.com. They suggested making a custom page template and having that page redirect to the first child. Perfect solution with one minor problem. Their code used wp_redirect() which, by default, uses a 302 redirect which is a temporary redirect. A better solution would be to use a 301 permanent redirect. Fortunately, the wp_redirect() function has an optional second parameter that let’s you put in what type of redirect to do.
And since I was editing the code anyway, even if it was only 4 characters (,301), I figured I’d rewrite it to make more sense to me. So here’s my version.
<?php /* Template Name: Redirect To First Child */ global $post; $postChildren = get_children(array( 'numberposts' => 1, 'orderby' => 'menu_order,title', 'order' => 'ASC', 'post_type' => 'page', 'post_status' => 'publish', 'post_parent' => $post->ID )); wp_redirect(get_permalink(array_pop($postChildren)->ID),301); ?>