WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Exclude a page and all its children from search results (1 post)

  1. Aldi
    Member
    Posted 2 years ago #

    Been looking for a way to exclude a page and all its children, including the grand-children, automatically from search results. Wasn't able to find it in the forum but managed to get hints here and there. So I came up with the script below. Thought I'd share it.

    <?php
    $parent = n; // 'n' for the ID of the parent page
    
    $children_data = get_pages( array(
    				'child_of' => $parent,
    				'post_type' => 'page'
    				) );
    
    $excludes = array($parent);
    
    foreach( $children_data as $child ) {
    	array_push($excludes, $child->ID);
    }
    
    global $wp_query;
    query_posts(
    	array_merge(
    		array('post__not_in' => $excludes),
    		$wp_query->query
    	)
    );
    
    if (have_posts()) : ?>

    The main code is the one above if (have_posts()).

Topic Closed

This topic has been closed to new replies.

About this Topic