WordPress ではウィジェットや get_calendar タグ/ファンクションを使って、ブログによくある投稿カレンダーを出力することができます。カレンダーの日付のリンク先は日付別アーカイブとなっているのですが、カレンダーの日付枠内に記事のタイトルを表示したいという要望がよくあります。巷ではイベントカレンダーと呼ばれるニーズですね。
そのようなことを実現するプラグインはありますが、他人のルールで作られたものは敬遠したいという方のために get_calendar をいじくる方法をご紹介します。さらにカレンダーに表示する記事はカテゴリーで指定できるようにします。
添削するのは、パーマリンクから日付を取得する正規表現。
if(preg_match_all('@<td><a href="' . get_option('home') . '/(\?m=)?([^"]*?)" title="[^"]*?">([0-9]+?)</a>@i', $output, $matches)){
foreach($matches[0] as $key => $match){
$date = preg_replace('@/@', '', $matches[2][$key]);
$year = substr($date, 0, 4); // 年
$month = substr($date, 4, 2); // 月
$day = substr($date, 6, 2); // 日
/* do stuff */
}
}
これだと、http://example.com/archives/date/2011/11/21 とかの形式に対応できない。
こんな感じに修正。
$date = preg_replace('@^[^0-9]*([0-9]+)/?(0[0-9]|1[0-2])/?([0-2][0-9]|3[01]).*$@', '$1$2$3', $matches[2][$key]);
// http://example.com/?m=201001 や http://example.com/201001 の月別アーカイブリンクを
// http://example.com/event-calendar/?ym=201001 の形式に変更する
// 前後月リンクは td に next, prev の ID が付加されているのでそれを利用する
if(preg_match_all(
'@<td( id="[prev|next]")?[^>]*?><a href="(' . get_option('home') . '/)(\?m=)?([^"]*?)" title="[^"]*?">[^<]+?</a>@i',
$output, $matches)){
foreach($matches[0] as $key => $match){
$ym = preg_replace('@/@', '', $matches[4][$key]);
$output = preg_replace(
'@' . preg_quote($matches[2][$key]) . preg_quote($matches[3][$key]) . preg_quote($matches[4][$key]) . '@',
get_permalink() . '/?ym=' . $ym,
$output
);
}
}
同様にこんな感じ。
$ym = preg_replace('@^[^0-9]*([0-9]+)/?(0[0-9]|1[0-2]).*$@', '$1$2', $matches[4][$key]);
コメントを残す