0

There is a filter on my list-view page of my custom post type (works)

add_action( 'pre_get_posts', array($this, 'exclude_category') );

public function exclude_category( $query){    
       if( is_admin() &&  isset( $_GET['cta_filter']) && ! empty( $_GET['cta_filter'] ) )
        {
            $term =  sanitize_text_field( $_GET['cta_filter'] );

            $query->tax_query->queries[] = array(
                'taxonomy' => 'cta_tax',
                'field'    => 'slug',
                'terms'    => array( $term ),
                'operator' => 'IN'
            );

            $query->query_vars['tax_query'] = $query->tax_query->queries;
        }
}

On the same page where i filter this posts i use get_posts() and it gives me only filtered posts but should return all posts. How can i prevent filtering my posts when i use get_posts() function.

2
  • There's ways to limit a pre_get_posts to a particular query, but it depends on what query are you trying to filter. Is your exclude_category function only intended for the main query? The archive? A widget? etc. Sep 12, 2017 at 12:20
  • I am trying to filter query only on list-view of posts in my cpt admin page. Sep 12, 2017 at 12:28

1 Answer 1

1

Check that the current query is the main query using $query->is_main_query().

add_action( 'pre_get_posts', array($this, 'exclude_category') );

public function exclude_category( $query){    
    if( is_admin() && $query->is_main_query() && isset( $_GET['cta_filter']) && ! empty( $_GET['cta_filter'] ) ) {
        $term = sanitize_text_field( $_GET['cta_filter'] );

        $tax_query = $query->get('tax_query') ?: array();

        $tax_query[] = array(
            'taxonomy' => 'cta_tax',
            'field'    => 'slug',
            'terms'    => array( $term ),
            'operator' => 'IN'
        );

        $query->set('tax_query',$tax_query):
    }
}

I'm assuming ?cta_filter= is only going to be set on your post type's admin page so no further conditions are necessary, but to be even safer you might want to add another condition:

&& 'post_type_name' === $query->get( 'post_type' )

Also note another change I made to your code. Rather than modifying query properties directly, I suggest using the get() and set() methods.

0

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.