WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Exclude post format from main query (3 posts)

  1. bob.passaro
    Member
    Posted 1 year ago #

    I'm wanting to use pre_get_posts to exclude some posts from my main query -- I want to include only 'standard' post formats in the main portion of the blog, and exclude 'video' and 'aside' post formats.

    The query I've got in place now sort of accomplishes what I want:

    <?php
    			$args = array(
    			'tax_query' => array(
    					array( 'taxonomy' => 'post_format',
    						  'field' => 'slug',
    						  'terms' => array('post-format-video','post-format-aside'),
    						  'operator' => 'NOT IN'
    						  )
    					)
    			);
    
    			$main_blog = new WP_Query();  // Main blog query
    			$main_blog->query( $args );
    		?>
    
    		<?php if ( $main_blog->have_posts() ) : while ( $main_blog->have_posts() ) : $main_blog->the_post(); //Main blog loop ?>

    But this isn't really the right way to change the main query, right? For one thing, it breaks the "older posts" link at the bottom of the home page.

    Can anyone help me with the code for using pre_get_posts to accomplish this. I guess I need to use tax_query? There doesn't seem to be any way to directly reference "post formats." Thank you!

  2. bob.passaro
    Member
    Posted 1 year ago #

    Hey, I got it working. Found this code on github, from one Bill Erickson (thanks, Bill!):

    function be_exclude_post_formats_from_blog( $query ) {
    
    	if( $query->is_main_query() && $query->is_home() ) {
    		$tax_query = array( array(
    			'taxonomy' => 'post_format',
    			'field' => 'slug',
    			'terms' => array( 'post-format-quote', 'post-format-image' ),
    			'operator' => 'NOT IN',
    		) );
    		$query->set( 'tax_query', $tax_query );
    	}
    
    }
    add_action( 'pre_get_posts', 'be_exclude_post_formats_from_blog' );

    Blog post explaining this: http://www.billerickson.net/customize-the-wordpress-query/

    How to deal with post formats isn't in the original post, but it comes up in the comment thread.

  3. bluantinoo
    Member
    Posted 9 months ago #

    This works perfectly, thanks for sharing bob!

Topic Closed

This topic has been closed to new replies.

About this Topic