script to sort posts by month on bear blog

Use this script if you want to display all your blog posts grouped by month.
### Step 1: Create a new page
1. Go to your Bear Blog dashboard
2. Navigate to **Pages** → **New Page**
3. Set the page slug to something like `archive` or `blog` (if blog is not your reserved blog path on bear)
### Step 2: Add the post embed code
In the editor, add the post embed code:
```html
Loading posts...
{{posts}}
```
> **Why the placeholder header?** The `` placeholder [prevents layout shift](tab:https://static.mighil.com/images/2025/1762754991494_mgx-bearblog-cls.webp) (CLS) when the JavaScript runs.
### Step 3: Add the JavaScript
You have two options:
**Option 1: Inline minified script (easiest)**
Add the JavaScript directly:
```html
Loading posts...
{{posts}}
```
**Option 2: External script (better for reusability)**
If you want to host the script elsewhere and load it:
1. Upload the [sort-posts-by-month.js](https://gist.github.com/verfasor/cf7b4455eb158fd65386149fd7b07d6f) to a CDN or your own hosting
2. Replace the inline script with:
```html
Loading posts...
{{posts}}
```
### How it works
1. **Initial Load**: Bear Blog renders all your posts using the `{{posts}}` embed code
2. **JavaScript Execution**: When the page loads, the script:
- Finds all post list items
- Groups them by month and year
- Finds the most recent post date
- Creates a header showing total count and last updated date
- Reorganizes posts under month headers (newest months first)
- Removes the original flat list
### The result
Your archive page will display [like this](tab:https://static.mighil.com/images/2025/1762682398301_script-to-sort-posts-by-month-on-bear-blog.webp):
```
{n} entries. Last updated on {lastUpdatedDate}.
November, 2025
- Post title 1
- Post title 2
October, 2025
- Post title 3
...
```
### Customization
You can customize the styling by targeting .archive:
```css
.archive {
margin-bottom: 2rem;
}
.archive-h3 {
margin-top: 2rem;
margin-bottom: 1rem;
}
.blog-posts {
list-style: none;
padding-left: 0;
}
```