the latest from 2am Media

20 Jun

WordPress – Exclude page children from the WP search results

BY

Want to exclude a page’s children from displaying in the search results? Heres how:

This example will exclude any child pages of 125 but only if the user is not logged in.

function SearchFilter($query) {
if ($query->is_search) {
if ( !is_user_logged_in() ) {
// exclude children of page 125
$parent = 125;
$children_data = get_pages( array(
'child_of' => $parent,
'post_type' => 'page'
) );
$excludes = array($parent);
foreach( $children_data as $child ) {
array_push($excludes, $child->ID);
}
$query->set('post__not_in', $excludes);
}
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');

Like what you see?

If you've got a web design or internet marketing project in mind and you think we're the team for you, pop in for a coffee and a chat...

Get in touch →