Code Snippet: WordPress Page Template Redirect to child page

Sometimes you need a simple way to redirect a parent page directly to it’s first child page in WordPress. This little snippet is a WordPress page template to be used in your theme. It includes support for WPML, in case you still use my least favourite translation plugin in the universe. I strongly suggest you use something like Polylang or Multilingual Press to create multilingual WordPress sites, but that’s material for another post.

Page Template

  * Template Name: Redirect to child page
  * Description: Redirects to the top child page

global $post; $parent = $post->ID;

// In case you use WPML
if ( defined( 'ICL_LANGUAGE_CODE' ) ) {
    $_type  = get_post_type( $post->ID );
    $parent = icl_object_id( $post->ID, $_type, true, ICL_LANGUAGE_CODE );
$post_children = get_children( array(
    'posts_per_page' => 1,
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'post_type' => 'page',
    'post_status' => 'publish',
    'post_parent' => $parent
) );
wp_redirect( get_permalink( array_pop( $post_children )->ID ), 301 );

Check out the gist for this page template.

Leave a comment

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

%d bloggers like this: