Support » Plugins » Hacks » Display child page content instead of parent

  • Resolved Tanel



    this post is not a question, but rather an explanation of how I managed to find a solution to my problem. Perhaps this will be useful for someone in the future.

    My problem was quite a common one: I have a site structure which looks like this:
    > Page A
    > Page B
    >> Subpage B.1
    >> Subpage B.2
    > Page C

    What I needed to achieve was to load the contents of Subpage B.1 instead of Page B when an user clicked on “Page B” link in the menu.

    There are a few solutions which use WP_Redirect, but I find them a bit messy + I can’t use a special template because my site has to be manageable by people who don’t know what “template” means (: Other way would be to create a check and a new query in my main page template file, but any way I looked at it, it always seemed like I needed to write my design stuff twice — once for non-subpages and once for subpages.

    So I investigated modifying the original WP_Query and long story short, this is how I’m doing it (it all goes to functions.php):

    // get first child id. returns false if no children exist. useful in other places as well.
    function first_child($pid) {
    	$children = get_pages("child_of=".$pid."&sort_column=menu_order");
    	if ($children) {
    		$firstchild = $children[0];
    		return $firstchild->ID;
    	} else {
    		return false;
    // modify the page main query
    add_action( 'pre_get_posts', 'replace_content_with_child' );
    function replace_content_with_child( $query ) {
    	$firstchild = first_child($query->queried_object_id);
    	if( $query->is_main_query() && !is_admin() && is_page() && $firstchild ) {
    		$query->query_vars['page_id'] = $firstchild;

    I’m not sure how “cheap” it is (should be quite?), but it keeps the template pages clean and seems to work well so far.

    I’m not a very professional developer, so if anyone happens to see errors or points of improvement (speed wise?!), all suggestions are welcome (:

  • The topic ‘Display child page content instead of parent’ is closed to new replies.