我一直在寻找一种方法来计算用户创建的自定义帖子的数量,并且能够使用此代码段进行操作:
<?php
$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'foo_type', $post_status = 'publish') {
global $wpdb;
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND post_type = '$post_type' AND post_status = '$post_status'";
$count = $wpdb->get_var($query);
return apply_filters('get_usernumposts', $count, $userid);
} ?>
然后用以下结果回显结果:
<?php echo count_user_posts_by_type($userid); ?>
我的问题:上面的代码只输出自定义帖子类型“foo_type”的计数。如果我有两个自定义帖子类型 - “foo_type”和“bar_type” - 如何更改此代码以便它返回两者的计数而不仅仅是“foo_type”的计数?
答案 0 :(得分:1)
将第二个post_type添加到查询中:
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND (post_type = '$post_type' OR post_type='$post_type_2') AND post_status = '$post_status'";
答案 1 :(得分:0)
尝试下面给出的自定义功能
function my_count_posts_by_user($post_author=null,$post_type=array(),$post_status=array()) {
global $wpdb;
if(empty($post_author))
return 0;
$post_status = (array) $post_status;
$post_type = (array) $post_type;
$sql = $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d AND ", $post_author );
//Post status
if(!empty($post_status)){
$argtype = array_fill(0, count($post_status), '%s');
$where = "(post_status=".implode( " OR post_status=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_status);
}
//Post type
if(!empty($post_type)){
$argtype = array_fill(0, count($post_type), '%s');
$where = "(post_type=".implode( " OR post_type=", $argtype).') AND ';
$sql .= $wpdb->prepare($where,$post_type);
}
$sql .='1=1';
$count = $wpdb->get_var($sql);
return $count;
}
然后用以下结果回显结果:
<?php echo my_count_posts_by_user($userid , array('posttype1' , 'posttype2')); ?>
请查看以下网址。
感谢
答案 2 :(得分:0)
$args = array(
'post_type'=> 'page',
'author' => '1',
'post_staus'=> 'publish',
'posts_per_page' => -1
);
echo custom_count_post_by_author($args);
function custom_count_post_by_author($args){
query_posts( $args );
$count = 0;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$count++;
endwhile;
endif;
wp_reset_query();
return $count;
}
您可以传递支持 query_posts 的$ args中的任何参数