4

UPDATE: I have the following code working. It excludes the taxonomy from the search results. However, I would like this only to happen if a user is not logged in. The code below is taking effect for logged in and logged out users. How can I check if someone is logged in from the functions.php file? I've tried !is_user_logged_in() many times, and I can't seem to get it to work? Thanks for any help!

add_filter( 'pre_get_posts', 'exclude_pages_search_when_logged_out' );
function exclude_pages_search_when_logged_out($query) {
    if ( $query->is_search && !is_user_logged_in() ) {

      $tax_query = array([
            'taxonomy' => 'wpfc_service_type',
            'field' => 'term_id',
            'terms' => [ 505 ],
            'operator' => 'NOT IN',
        ]);

        $query->set( 'tax_query', $tax_query );

        }

    return $query;
} 

ORIGINAL QUESTION

I'm trying to exclude the taxonomy 'wpfc_service_type', term 505, from my search results and archive pages. I've added the following to my functions.php file, but it doesn't seem to be working. What am I doing wrong?

    add_action( 'pre_get_posts', function ( $query ) {
        if ( is_admin() || ! $query->is_main_query() ) {
            return;
        }

        // Exclude Terms by ID from Search and Archive Listings
        if ( is_search() || is_tax( 'wpfc_service_type' ) ) {    
            $tax_query = array([
                'taxonomy' => 'wpfc_service_type',
                'field' => 'term_id',
                'terms' => [ 505 ],
                'operator' => 'NOT IN',
            ]);

            $query->set( 'tax_query', $tax_query );
        }
    }, 11, 1 ); 
0
0

Copy the following snippet and paste it into the code of your theme, preferably in the functions.php file:

    /* Exclude a Category from Search Results */

    add_filter( 'pre_get_posts' , 'search_exc_cats' );
    function search_exc_cats( $query ) {

    if( $query->is_admin )
    return $query;

    if( $query->is_search ) {
    $query->set( 'category__not_in' , array( 30 ) ); // Cat ID
    }
    return $query;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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