pre_get_posts with WP_Query to prevent posts from specific tags

I found this post about how to change a specific query but can't find a way to do the following:

  1. I have several queries on homepage retrieving posts from categories, posts from "New"s, posts from "Recipes", posts from "Promo" etc
  2. I have a slider area at the top that display posts from all categories that uses the tag "featured"

How can I prevent all other queries on home from retrieving posts using "featured" tag so posts using the tag do not show up at the same time on the others queries?

Obviously to change LL the other queries to not include posts using the tag would do, but to change the queries through pre_get_posts seems quite more neat.

Thanks for any help

Topic pre-get-posts wp-query Wordpress

Category Web


There's a couple problems I foresee here. I'm assuming the featured portion is a meta value of some sort. We can run a conditional that will run for all queries on the Front Page but it would override the meta_queries instead of append to them. The hook would look something like this:

/**
 * Modify Theme Queries
 *
 * @param WP_Query $query
 *
 * @return void
 */
function theme_pgp( $query ) {
    if( is_admin() ) {
        return;
    }

    if( $query->is_front_page() ) {

        if( false !== $query->get( 'post', false ) ) {
            $query->set( 'tag__not_in ' => array( 'Featured_Slug_ID' ) );
        }

    }
}

I don't know what your post type slug is or what your featured meta key is so it's a little difficult to create an exact exclusion query. Hopefully the above points you in the right direction though.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.