您最好的选择可能是使用$wpdb
直接地您可以使用COUNT
和GROUP BY
让事情变得更简单。
查询可能如下所示:
<?php
global $wpdb;
$res = $wpdb->get_results("SELECT MONTH(post_date) as post_month, count(ID) as post_count from {$wpdb->posts} WHERE post_status = \'publish\' GROUP BY post_month", OBJECT_K);
这让你大部分的路都走到了那里。请务必查看
generic results 第节
wpdb
文档。
要完成剩下的步骤,您可能需要循环1-12个范围,创建月份名称并检查结果是否包括该月份。
下面是一个实现为短代码的示例:
<?php
add_action(\'init\', \'wpse60859_register_shortcode\');
/**
* Registers the shortcode
*
* @uses add_shortcode
*/
function wpse60859_register_shortcode()
{
add_shortcode(
\'posts_per_month\',
\'wpse60859_shortcode_cb\'
);
}
/**
* The shortcode callback function.
*
* Usage:
* [posts_per_month year="2012"]
*
* @uses date_i18n
* @uses shortcode_atts
*/
function wpse60859_shortcode_cb($args)
{
global $wpdb;
$args = shortcode_atts(array(
\'year\' => false
), $args);
$year = absint($args[\'year\']);
// year is a no go? bail.
if(!$year)
return \'\';
$res = $wpdb->get_results($wpdb->prepare(
"SELECT MONTH(post_date) AS post_month, count(ID) AS post_count from " .
"{$wpdb->posts} WHERE post_status = \'publish\' AND YEAR(post_date) = %d " .
"GROUP BY post_month;", $year
), OBJECT_K);
// We didn\'t get any results. Something might be wrong?
if(!$res)
return \'\';
// build the display
$out = \'<ul>\';
foreach(range(1, 12) as $m)
{
$month = date_i18n(\'F\', mktime(0, 0, 0, $m, 1));
$out .= sprintf(
\'<li>%s %d</li>\',
$month,
isset($res[$m]) ? $res[$m]->post_count : 0
);
}
$out .= \'</ul>\';
return $out;
}
The
foreach
最后的循环是需要注意的。在1-12范围内循环,为每个月创建一个正确的月份名称,然后查看是否存在post计数。如果它确实使用该数字,或者打印0。
那个短代码as a plugin.
EDIT 显示过去12个月的计数。
这需要一个更复杂的查询,但概念是一样的:按月分组获取帖子数量。这一次,订单按邮寄日期升序。从那里,我们只需要根据当前日期创建一个月数数组。
示例(再次作为短代码)
<?php
add_action(\'init\', \'wpse60859_register_shortcode\');
/**
* Registers the shortcode
*
* @uses add_shortcode
*/
function wpse60859_register_shortcode()
{
add_shortcode(
\'posts_per_month_last\',
\'wpse60859_shortcode_alt_cb\'
);
}
/**
* Callback for displaying the last twelve months of posts
*
* @uses $wpdb
*/
function wpse60859_shortcode_alt_cb()
{
global $wpdb;
$res = $wpdb->get_results(
"SELECT MONTH(post_date) as post_month, COUNT(ID) as post_count " .
"FROM {$wpdb->posts} " .
"WHERE post_date BETWEEN DATE_SUB(NOW(), INTERVAL 12 MONTH) AND NOW() " .
"AND post_status = \'publish\' " .
"GROUP BY post_month ORDER BY post_date ASC", OBJECT_K
);
$cur = absint(date(\'n\'));
if($cur > 1)
{
$looper = array_merge(range($cur, 12), range(1, $cur-1));
}
else
{
$looper = range(1, 12);
}
$out = \'<ul>\';
foreach($looper as $m)
{
$month = date_i18n(\'F\', mktime(0, 0, 0, $m, 1));
$out .= sprintf(
\'<li>%s %d</li>\',
$month,
isset($res[$m]) ? $res[$m]->post_count : 0
);
}
$out .= \'</ul>\';
return $out;
}