Post Format Views with Categories and Tags

I think it makes a lot of sense to display certain post format archives differently than standard post archives. For instance, image post formats might look a lot better in a grid view with large images rather than a traditional blog format.

It’s easy enough to alter the post format archive template, but the taxonomy views (categories and tags) will still display in the standard layout- even if all the posts are the same format.

I thought it would be great to detect what type of posts were being displayed in the taxonomy before they rendered, and use a different layout if they were all in the same post format. This way I could continuity between the post format archives and taxonomy archives- assuming they all contained the same post format.

This loop allows us to detect if all the posts are image or gallery post formats:

$portfolio_view = true;
global $wp_query;
if ( $wp_query->have_posts() ) :
	while ( $wp_query->have_posts() ) : $wp_query->the_post();
		$format = get_post_format();
		if ( ( $format != 'image' ) && ( $format != 'gallery' ) ) {
			$portfolio_view = false;
		}
	endwhile;
endif;

if ( $portfolio_view ) {
	// All image or gallery post formats
}

By using this code in the template_include hook, we can run the check before the post render, and then call a different template to display the content if it meets our conditions (such as our post type archive template).

function prefix_template_chooser( $template ) {

	// Check if the taxonomy query contains only image or gallery post formats
	if ( is_category() || is_tag() ) {
		$portfolio_view = true;
		global $wp_query;
		if ( $wp_query->have_posts() ) :
			while ( $wp_query->have_posts() ) : $wp_query->the_post();
				$format = get_post_format();
				if ( ( $format != 'image' ) && ( $format != 'gallery' ) ) {
					$portfolio_view = false;
				}
			endwhile;
		endif;
		if ( $portfolio_view ) {
			// In this case, I'm using an archive-portfolio template I've created
			$template = get_query_template( 'archive-portfolio' );
		}
	}

	return $template;
}
add_filter( 'template_include', 'prefix_template_chooser' );

This is kind of a magical hook. Have fun with it!

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

Leave a Reply