0

I am trying to exclude pages from my search result with this function:

function posts_for_current_author($query) {
    global $user_level;

    if($query->is_admin && $user_level < 5) {
        global $user_ID;
        $query->set('author',  $user_ID);
        unset($user_ID);
    }
    unset($user_level);


    if ($query->is_search && $query->is_main_query()) {
        $query->set('posts_per_page', 9);
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter('pre_get_posts', 'posts_for_current_author');

In if($query->is_search) i have a $query->set( 'post_type', 'post' ); but that one does not want to work, even though $query->set('posts_per_page', 9); works... So my mind is blown here. Anyone know how to fix this?

2
  • 1
    your code works for me when I test with twentysixteen, make sure you don't have other filters altering the query elsewhere.
    – Milo
    Commented Mar 30, 2016 at 20:51
  • Hmm, must be the theme that's destroying the function then. I'll check for what you said @Milo. Thanks
    – Rasmus
    Commented Mar 31, 2016 at 9:53

1 Answer 1

0

After Milo's help I found a function where it altered the search query:

if( is_search() && empty($_GET['post_type']) && !is_admin() ) {
                global $wpdb;
                $query = get_search_query();
                $query = $wpdb->esc_like( $query );

                $where .= " OR {$wpdb->posts}.ID IN (";
                $where .= "SELECT {$wpdb->postmeta}.post_id ";
                $where .= "FROM {$wpdb->posts}, {$wpdb->postmeta} ";
                $where .= "WHERE {$wpdb->posts}.post_type = 'page' ";<-page to post
                $where .= "AND {$wpdb->posts}.post_status = 'publish' ";
                $where .= "AND {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id ";
                $where .= "AND {$wpdb->postmeta}.meta_key IN('above-sidebar', 'content-with-sidebar', 'below-sidebar') ";
                $where .= "AND {$wpdb->postmeta}.meta_value LIKE '%$query%' )";
            }
            return $where;

I changed post_type ='page' to 'post' and now it works perfectly.

Thanks again, Milo!

Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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