我有一个按类型统计帖子数量的函数(摘自wordpress codex)
function count_user_posts_by_type($userid, $post_type) {
global $wpdb;
$where = get_posts_by_author_sql($post_type, TRUE, $userid);
$count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} $where" );
return apply_filters(\'get_usernumposts\', $count, $userid);
}
我修改了它,以便显示状态为“草稿”和“待定”的帖子。
function count_user_posts_by_type($userid, $post_type) {
global $wpdb;
$where = get_posts_by_author_sql($post_type, TRUE, $userid);
$count = $wpdb->get_var( "SELECT COUNT(*)
FROM {$wpdb->posts} $where
AND (post_status = \'publish\' OR post_status = \'draft\' OR post_status = \'pending\')");
return apply_filters(\'get_usernumposts\', $count, $userid);
}
但它不起作用。如果我像这样回显函数
echo count_user_posts_by_type(wp_get_current_user()->ID, \'percorso\');
我可以看到,它只统计发布的帖子。我写的东西怎么了?谢谢
编辑:根据建议,我为SELECT COUNT等执行了var\\u转储。下面是我得到的
string(216)
"SELECT COUNT(*) FROM mi_posts
WHERE post_author = 1
AND post_type = \'percorso\'
AND (post_status = \'publish\' OR post_status = \'private\')
AND (post_status = \'publish\' OR post_status = \'draft\' OR post_status = \'pending\')"
最合适的回答,由SO网友:brasofilo 整理而成
没有必要使用$wpdb
, 一个简单的get_posts
我能应付。检查WP_Query
获取完整的参数列表。
function count_user_posts_by_type( $userid, $post_type )
{
$args = array(
\'numberposts\' => -1,
\'post_type\' => $post_type,
\'post_status\' => array( \'publish\', \'private\', \'draft\', \'pending\' ),
\'author\' => $userid
);
$count_posts = count( get_posts( $args ) );
return $count_posts;
}