Redirect to first subpage

If you want to redirect the page to first subpage then create new WordPress template file in your main theme, for example redirect-to-first-subpage.php and put folowing code in it. Then edit necessary page (which will be redirected) and setup "Page Template" as "Redirect to first subpage".

<?php
/*
Template Name: Redirect to first subpage
*/
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post();
		$subpages_args = array(
			'sort_column'  => 'menu_order, post_title',
			'child_of' => $post->ID
		);
		$subpages = get_pages( $subpages_args );
		if ( $subpages ) {
			$first_subpage = $subpages[0];
			wp_redirect( get_permalink( $first_subpage->ID ) );
		}
	}
}
?>

Leave a Comment