Exclude add_filter from the admin

I’ve created a custom filtering facility for a front end search, which also includes a specific user group.

To add the function to the search I have used

Read More
add_filter('pre_get_posts','my_filter_the_search',10,1);

function my_filter_the_search($query){

    $post_type = filter_input(INPUT_GET, 'post_type', FILTER_SANITIZE_STRING);

    if($post_type == 'document'):

        add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

        //Get array of slugs of checked terms
        $terms = (array) $_GET['post_type'];



        //Tax_query array
        $tax_query = array(array(
            'taxonomy' => 'access',
            'terms' => 'basic-user',
            'field' => 'slug',
        ));


        //Tell the query to filter by tax
        $query->set('tax_query', $tax_query);

        return $query;

    endif;
}

This appears to be effecting the listing of a custom post type in the backend.

How do I only use this for the front end of the site?

Related posts

2 comments

  1. Only hook the function if its not the backend.

    if( !is_admin() ){
        add_filter('pre_get_posts','my_filter_the_search',10,1);
    }
    
  2. Just do a var_dump( $query ); inside your callback to see the objects properties. One of the property you can use is is_admin.

    // functions.php
    function my_search_filter($query) {
        if ( $query->is_admin ) {
            // do/set something on query
            return $query;
        }
    
        return $query;
    }
    add_filter('pre_get_posts','my_search_filter');
    

    Using is_admin() global function is also fine.

Comments are closed.