Adapt listing layout based on number of items

The Post Grid styling works great if you know how many posts will be returned, but it doesn’t look good to have a single post in a 3 column grid.

The code below will add an additional class to the wrapper indicating the number of posts in the result (ex: count-4). You can then adjust the styling of the grid based on that.

This code snippet goes in a core functionality plugin or Code Snippets.

/**
 * Display Posts, add post count as wrapper class
 * @see https://displayposts.com/2019/02/25/adapt-listing-layout-based-on-number-of-items/
 *
 */
function be_dps_count_wrapper_class( $output, $atts, $listing ) {
	$class = 'count-' . intval( $listing->post_count );
	$output = str_replace( 'class="', 'class="' . $class . ' ', $output );
	return $output;
}
add_filter( 'display_posts_shortcode_wrapper_open', 'be_dps_count_wrapper_class', 10, 3 );

You can then change the grid styling based on the count.

The Post Grid styling displays in 2 columns on tablet, 3 columns on desktop. The shortcode looks like: [display-posts wrapper_class="display-posts-listing grid"].

The CSS below changes the layout based on the number of posts:

  • If there’s a single post, always display it full width.
  • If there are 2 or 4 posts, display in 2 columns on desktop.

This code snippet goes in Appearance > Customize > Additional CSS or your theme’s stylesheet.

@media (min-width: 600px) {
	.display-posts-listing.grid.count-1 {
		display: block;
	}
}

@media (min-width: 1024px) {
	.display-posts-listing.grid.count-2,
	.display-posts-listing.grid.count-4, {
		grid-template-columns: repeat( 2, 1fr );
	}
}

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.