Menü schliessen
Created: December 18th 2023
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to redirect to first child page

Tags:  guide,  PHP,  Template,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In the realm of website development, the efficiency of user navigation plays a crucial role in enhancing the overall browsing experience. The following page template can be used for redirecting to a page's first child page.


Template

<?php

/*
Template Name: Redirect to 1st child page
*/

$children = get_children([
	'post_parent'      => get_post()->ID,
	'post_type'        => 'page',
	'numberposts'      => 1,
	'orderby'          => 'menu_order',
    'order'            => 'ASC',
    'post_status'      => 'publish',
]) ?: [];

if (!empty($children)) {
	nocache_headers();

	foreach ($children as $child) {
		if (wp_safe_redirect(get_permalink($child), 301)) {
			exit;
		}
	}
}

require_once('page.php');

?>

How it works

  • Template Definition: The template is declared with the name "Redirect to 1st child page", enabling its selection from within the WordPress dashboard.
  • Fetching Child Pages: Utilizing get_children(), the template retrieves child pages of the current parent page. These child pages are ordered by menu order to maintain consistency with site navigation.
  • Redirecting to First Child: If child pages are present, the template redirects the user to the first child page using wp_safe_redirect(). This redirection is permanent (301), indicating to search engines that the page has moved permanently.
  • Ensuring Clean Redirection: To prevent caching issues and maintain integrity, nocache_headers() is invoked before redirection.
  • Fallback Mechanism: In the absence of child pages, the template defaults to the regular page template (page.php).