WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Exclude post format from main query

[Resolved] Exclude post format from main query

  • bob.passaro

    @bobpassaro

    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!

Viewing 2 replies - 1 through 2 (of 2 total)
  • bob.passaro

    @bobpassaro

    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.

    This works perfectly, thanks for sharing bob!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[Resolved] Exclude post format from main query’ is closed to new replies.