> For the complete documentation index, see [llms.txt](https://wplake.gitbook.io/advanced-views/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wplake.gitbook.io/advanced-views/post-selections/guides/group-posts-by-field.md).

# How to group Posts by field

In Advanced Views, the [*Post Selection*](/advanced-views/getting-started/first-post-selection.md) interface supports sorting but does not provide built-in grouping options. To display results grouped by a specific field, you'll need to customize the [Selection Controller](/advanced-views/post-selections/code-fields/selection-controller.md).

This step-by-step guide demonstrates how to display **Event** custom post type items grouped by a date field.

## 1. Preparations

1. First, create your Field Group with the fields; in this case, it's Event Date (date) assigned to a Custom Post Type (CPT) called Events.
2. Visit the **Advanced Views** tab in the WordPress backend.

## **2. &#x20;*****Layout creation***

1. Click the **Add New** **Layout** button to add a new *Layout, then* enter a **Name** for your *Layout*.&#x20;
2. Click the **Add Field** button in the Assign *Fields* section. Then **select** the target *Group* from the list and the *Field* from the dropdown. Continue to **Add Fields** that should be included. In our case, we're only adding two fields: Title with Link and Date.

<figure><img src="/files/Z2IvXVGABbZg6DJW8G4C" alt=""><figcaption></figcaption></figure>

3. Click on the **Publish** button to save and publish your *Layout*.&#x20;

## **3.** *Post Selection* **creation**

1. Use the "Add new" button under 'Assigned to Post Selections' in the right sidebar of your Layout, or simply go to the *Post Selections* top tab.
2. Click the **Add New Post Selection** button to add a new *Post Selection*, then enter a Name for your item.
3. On the General tab choose Item Layout 'event', select Post Type Event, for Sort by "Meta value", with the Sort by Meta Field Group the one containing the date field, in our case it's 'Date(ACF)'. Then,, for Sort by Meta Field, select 'Date (date\_picker)' with Sort order "Ascending," i.e. alphabetical (This is important; otherwise, the grouping won't work correctly).

<figure><img src="/files/dQyWeUnOCf3pTJBUHOEt" alt=""><figcaption></figcaption></figure>

4. Switch to the Advanced tab and scroll down to Selection Controller and insert the function snippet below. Replace your field name with "date".

```php
<?php

declare(strict_types=1);

use Org\Wplake\Advanced_Views\Bridge\Controllers\Selection\Selection_Controller_Base;

return new class extends Selection_Controller_Base {
    // ...other methods go here.
    public function get_variables(): array
    {
        $post_ids = $this->get_default_variables()["_selection"]['post_ids'] ?? [];
        $grouped_items = [];

        foreach ($post_ids as $post_id) {

            // declare the field to group by
            $raw_date = get_field('date', $post_id); // ACF date field

            // convert to month string
            $month = "";
            if ($raw_date) {
                $timestamp = strtotime($raw_date);
                $month = $timestamp ? date('F Y', $timestamp) : 'No Date';
            } else {
                $month = 'No Date';
            }

            // initialize group if not exists
            if (!key_exists($month, $grouped_items)) {
                $grouped_items[$month] = [];
            }

            // add post to group
            $grouped_items[$month][] = $post_id;
        }

        return [
            "grouped_items" => $grouped_items,
        ];
    }
};
```

5. Switch to the Template tab, and copy your Default template content into the Custom template field below it.

Modifying from line 4 -> 18.

<pre class="language-twig" data-overflow="wrap" data-line-numbers><code class="lang-twig"><strong>// Selection template example
</strong>&#x3C;avf-selection-69a3ee57020ca class="{{ _selection.classes }}avf-selection avf-selection--id--{{ _selection.id }}">

	{% if _selection.post_ids %}
		&#x3C;div class="avf-selection__items">   
			{% for date, post_ids in grouped_items %}
            {{ date }}
            &#x3C;hr>
                {% for post_id in post_ids %}
                    [avf-layout id="{{ _selection.view_id }}" object-id="{{ post_id }}"]
                {% endfor %}
      {% endfor %}		
		&#x3C;/div>
	{% else %}
		&#x3C;div class="avf-selection__no-posts-message">{{ _selection.no_posts_found_message }}&#x3C;/div>
	{% endif %}

&#x3C;/avf-selection-69a3ee57020ca>
</code></pre>

6. Publish or save your *Post Selection* and copy the shortcode into place.

Remember to create your event posts and fill out some information in the fields.

<figure><img src="/files/pqFOlmyXBCHKU0OccMBN" alt=""><figcaption></figcaption></figure>
