功能需求
- 顯示指定年月日曆,預設當月。
- 有文章的日期高亮/標記,點擊跳轉文章列表。
- 上一月/下一月導航 (支援 AJAX 無刷新切換)。
- 響應式表格佈局,支援行動裝置。
資料庫結構 (範例)
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
content TEXT,
published_at DATETIME NOT NULL,
status ENUM('draft','published') DEFAULT 'published'
);
後端核心類別
<?php
class Calendar {
private PDO $pdo;
private string $table = 'posts';
private string $dateColumn = 'published_at';
public function __construct(PDO $pdo) { $this->pdo = $pdo; }
/** 獲取指定年月的文章日期分佈 */
public function getPostsByMonth(int $year, int $month): array {
$start = "$year-$month-01 00:00:00";
$end = date('Y-m-t 23:59:59', strtotime($start));
$sql = "SELECT DATE({$this->dateColumn}) as day, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
FROM {$this->table}
WHERE {$this->dateColumn} BETWEEN ? AND ? AND status='published'
GROUP BY DATE({$this->dateColumn})";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([$start, $end]);
$map = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$day = (int)date('j', strtotime($row['day']));
$map[$day] = ['count' => (int)$row['cnt'], 'ids' => explode(',', $row['ids'])];
}
return $map;
}
/** 渲染日曆 HTML (可直接輸出或返回字串) */
public function render(int $year = 0, int $month = 0, bool $ajax = false): string {
$year = $year ?: (int)date('Y');
$month = $month ?: (int)date('m');
$postsMap = $this->getPostsByMonth($year, $month);
$firstDayOfWeek = (int)date('N', strtotime("$year-$month-01")); // 1=Mon..7=Sun
$daysInMonth = (int)date('t', strtotime("$year-$month-01"));
$prevMonth = $month === 1 ? 12 : $month - 1;
$prevYear = $month === 1 ? $year - 1 : $year;
$nextMonth = $month === 12 ? 1 : $month + 1;
$nextYear = $month === 12 ? $year + 1 : $year;
$navUrl = $ajax ? "javascript:loadCal($prevYear,$prevMonth)" : "?y=$prevYear&m=$prevMonth";
$nextUrl = $ajax ? "javascript:loadCal($nextYear,$nextMonth)" : "?y=$nextYear&m=$nextMonth";
$html = '';
if (!$ajax) {
$html .= '<div class="calendar-wrap">';
}
$html .= '<div class="cal-header">';
$html .= '<a href="' . $navUrl . '" class="cal-nav prev">‹</a>';
$html .= '<h3>' . $year . '年' . $month . '月</h3>';
$html .= '<a href="' . $nextUrl . '" class="cal-nav next">›</a>';
$html .= '</div>';
$html .= '<table class="cal-grid"><thead><tr>';
foreach (['一','二','三','四','五','六','日'] as $w) $html .= "<th>$w</th>";
$html .= '</tr></thead><tbody><tr>';
// 前導空白
for ($i = 1; $i < $firstDayOfWeek; $i++) $html .= '<td class="empty"></td>';
for ($day = 1; $day <= $daysInMonth; $day++) {
$cellClass = '';
$cellContent = $day;
if (isset($postsMap[$day])) {
$cellClass = 'has-posts';
$count = $postsMap[$day]['count'];
$ids = $postsMap[$day]['ids'];
// 簡單:點擊跳轉列表頁帶日期參數
$listUrl = "/posts/list.php?date=$year-$month-" . str_pad($day,2,'0',STR_PAD_LEFT);
$cellContent = "<a href='$listUrl' class='day-link'>$day<span class='badge'>$count</span></a>";
}
$isToday = ($year == date('Y') && $month == date('m') && $day == date('j'));
if ($isToday) $cellClass .= ' today';
$html .= "<td class='$cellClass'>$cellContent</td>";
// 換行
if ((($firstDayOfWeek - 1 + $day) % 7) === 0 && $day < $daysInMonth) {
$html .= '</tr><tr>';
}
}
// 結尾空白
$lastWeekDay = (($firstDayOfWeek - 1 + $daysInMonth) % 7);
if ($lastWeekDay !== 0) {
for ($i = $lastWeekDay + 1; $i <= 7; $i++) $html .= '<td class="empty"></td>';
}
$html .= '</tr></tbody></table>';
if (!$ajax) $html .= '</div>';
return $html;
}
}
前端整合 (index.php)
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>部落格日曆</title>
<style>
.calendar-wrap { max-width: 700px; margin: 2rem auto; font-family: system-ui; }
.cal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; }
.cal-nav { text-decoration:none; font-size:1.5rem; color:#333; }
.cal-grid { width:100%; border-collapse:collapse; }
.cal-grid th, .cal-grid td { width:14.28%; height:80px; vertical-align:top; border:1px solid #eee; padding:.5rem; }
.cal-grid th { background:#f8f9fa; font-weight:600; }
.cal-grid .empty { background:#fafafa; }
.cal-grid .today { background:#fff3cd; }
.cal-grid .has-posts .day-link { display:block; text-decoration:none; color:#0d6efd; font-weight:bold; }
.cal-grid .badge { background:#0d6efd; color:#fff; font-size:.7rem; padding:.1rem .4rem; border-radius:.5rem; margin-left:.3rem; }
@media (max-width: 480px) { .cal-grid th, .cal-grid td { height:60px; font-size:.85rem; } }
</style></head><body>
<div id="calendar">
<?php
require 'Calendar.php';
$pdo = new PDO('mysql:host=localhost;dbname=blog;charset=utf8mb4', 'user', 'pass');
$cal = new Calendar($pdo);
echo $cal->render(); // 首次渲染
?>
</div>
<script>
// AJAX 切換月份
function loadCal(year, month) {
fetch('calendar_ajax.php?y=' + year + '&m=' + month)
.then(r => r.text())
.then(html => document.getElementById('calendar').innerHTML = html);
}
</script>
</body></html>
AJAX 端點 (calendar_ajax.php)
<?php
require 'Calendar.php';
$pdo = new PDO('mysql:host=localhost;dbname=blog;charset=utf8mb4', 'user', 'pass');
$cal = new Calendar($pdo);
$y = (int)($_GET['y'] ?? date('Y'));
$m = (int)($_GET['m'] ?? date('m'));
echo $cal->render($y, $m, true); // true = ajax 模式,不輸出外層 wrap
擴展建議
- 加入「本月文章總數」統計顯示。
- 支援多作者過濾 (
author_id)。
- 整合全文搜尋:點擊日期彈出模態框顯示文章列表 (AJAX 獲取)。
- 快取:
getPostsByMonth 結果可快取 5-10 分鐘 (Redis/APCu)。