WordPress查询某年某月文章的SQL语句
脚本之家
利用$wpdb自定义查询可以调用某年下的月份归档, 例如调用2014年月份归档的代码如下所示。
// Get archive by year
global $wpdb, $wp_locale;
$year = 2014;
$query = "SELECT DISTINCT MONTH(post_date) AS `month` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' AND YEAR(post_date) = $year ORDER BY `month` DESC";
$months = $wpdb->get_results($query);
echo '<ul>';
echo '<li><a href="'.get_year_link( $year ).'">'.sprintf('%d', $year).'</a>';
echo '<ul class="month-list">';
foreach( $months as $month ) {
$text = sprintf(__('%1$s'), $wp_locale->get_month($month->month));
echo '<li><a href="'.get_month_link( $year, $month->month).'">'.$text.'</a></li>';
}
echo '</ul></li></ul>';
global $wpdb, $wp_locale;
$year = 2014;
$query = "SELECT DISTINCT MONTH(post_date) AS `month` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' AND YEAR(post_date) = $year ORDER BY `month` DESC";
$months = $wpdb->get_results($query);
echo '<ul>';
echo '<li><a href="'.get_year_link( $year ).'">'.sprintf('%d', $year).'</a>';
echo '<ul class="month-list">';
foreach( $months as $month ) {
$text = sprintf(__('%1$s'), $wp_locale->get_month($month->month));
echo '<li><a href="'.get_month_link( $year, $month->month).'">'.$text.'</a></li>';
}
echo '</ul></li></ul>';
输出如下:
<ul>
<li><a href="http://yourdomain.com/2013/">2013</a>
<ul class="month-list">
<li><a href="http://yourdomain.com/2013/11/">十一月</a></li>
<li><a href="http://yourdomain.com/2013/09/">九月</a></li>
<li><a href="http://yourdomain.com/2013/08/">八月</a></li>
<li><a href="http://yourdomain.com/2013/06/">六月</a></li>
<li><a href="http://yourdomain.com/2013/02/">二月</a></li>
</ul>
</li>
</ul>
<li><a href="http://yourdomain.com/2013/">2013</a>
<ul class="month-list">
<li><a href="http://yourdomain.com/2013/11/">十一月</a></li>
<li><a href="http://yourdomain.com/2013/09/">九月</a></li>
<li><a href="http://yourdomain.com/2013/08/">八月</a></li>
<li><a href="http://yourdomain.com/2013/06/">六月</a></li>
<li><a href="http://yourdomain.com/2013/02/">二月</a></li>
</ul>
</li>
</ul>