Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

With the following code I can exclude all posts and pages that are top-level, but I would like to apply this only to pages, not to posts (but I still want all posts in the results):

function search_filter( $query )
{
    if(
        $query->is_search 
        AND $query->is_main_query()
        )
    {
        $query->set( 'post_parent__not_in', array( 0 ) );
        $query->set( 'post_type', array( 'post', 'page' ) );
    }
    return $query;
}

At the moment all my posts have 0 as post_parent, so they all get excluded from the results.

share|improve this question
    
Did you try changing the post_type only to page instead of post and page like $query->set( 'post_type', array( 'page' ) ) –  Maruti Mohanty Oct 30 '13 at 12:34
    
You should take a closer look at the posts_where and/or posts_search filter. –  ialocin Oct 30 '13 at 13:37
    
Any luck so far? –  birgire Oct 31 '13 at 15:26
add comment

1 Answer

I wonder if this will work for you:

function search_filter( $query )
{
    if( $query->is_search AND $query->is_main_query() )
    {
        // $query->set( 'post_parent__not_in', array( 0 ) ); // We comment this out here 
        $query->set( 'post_type', array( 'post', 'page' ) );
    }
    return $query;
}
add_action( 'pre_get_posts', 'search_filter' );

and

function wpse_120638( $where, $query ) 
{
    global $wpdb;

    if( $query->is_search AND $query->is_main_query() )
    {
            $from = "AND $wpdb->posts.post_type IN ('post', 'page')";
            $to   = "AND ( ( $wpdb->posts.post_parent NOT IN (0) 
                     AND $wpdb->posts.post_type IN ('page') ) 
                     OR $wpdb->posts.post_type IN ('post') ) ";

        $where = str_replace( $from, $to, $where );                                   
    }

    return $where;
}
add_filter( 'posts_where', 'wpse_120638', 10, 2 );
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.