Group custom post type posts by month

The basic principle here is that you don’t need to really ‘group’ posts, per se. So no query magic is required (it just needs to be sorted by date, which is the default). What you’re doing is that as you go through the list of posts, you make note of the month that the post belongs to, then when that month is different to the previous posts’ month, that means you’ve entered a new group of posts, and should output the heading.

In your context, when dealing with the post publication date, you want to use get_the_date(), but with the format set to F Y, which is “February 2019”, for example, which is how the posts are being grouped. You could group posts by day by including the day in the date format.

So all together, you have:

// Initialize the current month as null, so that the first group's heading is output.
$current_month = null;

while ( have_posts() ) : the_post();
    // Compare month of this post, to the current month.
    $this_month = get_the_date( 'F J' );

    // If we're in a new month, output the month heading.
    if ( $this_month !== $current_month ) {
        echo '<h2>' . $this_month . '</h2>';
    }

    // Set the current month to the month of the current post.
    $current_month = $this_month;

    // Display post here.
endwhile;