Group Posts by anything in a View Loop

Sometimes we want to group posts in a View and display certain details for each group of posts. The most common use case is a list of posts with their Dates as headings, where several posts share the same date.

To achieve this, you can register the following ShortCode

//group by month and year
add_shortcode('heading', 'my_heading');
  
function my_heading($atts, $content = '') {
  static $year = null;
  static $month = null;
  $condition = $atts['condition'];;
  $value = $atts['value'];;
  switch ($condition) {
    case 'year':
    case 'month':
      if ($$condition != $value) {
        $$condition = $value;
        return $content;
      }
      break;
  }
  return '';
}

And then use it like this in a Views Loop:

[heading condition="year" value="[wpv-post-date format="Y"]"]
<h4>[wpv-post-date format="Y"]</h4>
[/heading]
  
[heading condition="month" value="[wpv-post-date format="F"]"]
<h5>[wpv-post-date format="F"]</h5>
[/heading]
  
<h4>[wpv-post-title]</h4>
[wpv-post-excerpt]