Issue with pre_get_posts on custom post type archive pages

If we look in source, we’ll see under what conditions is_archive is true: if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax ) $this->is_archive = true; The issue is that is_archive is triggering your filter on your post type archive. If you want to exclude those, either make sure it’s not … Read more

How to alter the query using pre_get_posts hook and is_post_type_archive

You should be using methods of the $query instance instead of the is_* template tags. And are the categories you are trying to filter a custom taxonomy? cat only works on the default category taxonomy: function wpse_178500_event_type_filter( $wp_query ) { if ( ! empty( $_GET[‘event_term’] ) && $wp_query->is_main_query() && $wp_query->get( ‘post_type’ ) === ‘event’ ) … Read more

Using more than one meta_key in pre_posts_query

Use WP_Query to select any post based on meta key and value. You can also sort posts Ex: $args = array( ‘post_type’ => ‘events’, ‘orderby’ => ‘meta_value_num’, //probably you will need this because the value is date ‘meta_key’ => ‘event_date’, ‘meta_query’ => array( ‘relation’ => ‘AND’, array( ‘key’ => ‘event_status’, ‘value’ => $retrieved_status, ‘compare’ => … Read more

How to change posts order on Category and Tag archives?

You can use pre_get_posts action to modify this order. Here’s the code: function my_change_posts_order( $query ){ if ( ! is_admin() && ( is_category() || is_tag() ) && $query->is_main_query() ) { $query->set( ‘order’, ‘ASC’ ); } }; add_action( ‘pre_get_posts’, ‘my_change_posts_order’); What we do here is: We’re adding our function that will modify params for WP_Queries We … Read more

pre_get_posts for exclude category

$caid is unknown inside the function, unless declared global. $caid = ‘-1’; function exclude_category( $query ) { global $caid; if ( $query->is_home() && $query->is_main_query() ) { $query->set( ‘cat’, $caid ); } } add_action( ‘pre_get_posts’, ‘exclude_category’ ); // Edit Do you need the variable outside the function at all? If not, just move it inside the … Read more

How do I sort posts by custom taxonomy?

If I understand your question correctly, I think I may have your answer in this blog post: https://evowebdev.com/2017/05/using-a-dropdown-menu-to-filter-a-custom-post-type-with-custom-taxonomy/ This solution specifically uses select form element auto-populated with taxonomy terms to sort CPT posts (ie, rather than presorting posts with pre_get_posts, it lets site visitors sort by the taxonomy term[s] they select). If it’s really important … Read more