WordPress first child page redirect shortcode

It seems most people are using page templates when they need a parent page to redirect to the first child page. I wanted to make a shortcode, so I could include it in a plugin pack. I ran into an issue with headers already being sent, but found a solution.

I also needed my redirect to go to the first child even if I was excluding it from the menu using the Exclude Pages plugin. Thankfully the plugin includes a couple handy functions that make it possible to list excluded pages.

Here’s what I came up with. It works pretty well.

add_shortcode('firstChildRedirect', 'firstChildRedirect_shortcode');

function firstChildRedirect_shortcode(){

	//pauses "Exclude Pages" so no pages are excluded from redirection list
	if( function_exists("pause_exclude_pages") ) pause_exclude_pages();
	global $post;
    $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order");
    $firstchild = $pagekids[0];
	if( function_exists("resume_exclude_pages") ) resume_exclude_pages();
	wp_redirect( get_permalink($firstchild->ID), 301 );
	exit;

};

Just add this to your functions.php or make a basic plugin.

Mjenn123

This is where you’ll find an amazing bio all about me when I get around to writing one.

Leave a Reply