1

我一直在寻找一种方法来计算用户创建的自定义帖子的数量,并且能够使用以下代码段来做到这一点:

<?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”的计数?

4

3 回答 3

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'"; 
于 2012-12-28T10:17:39.900 回答
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')); ?>

请看下面给出的网址..

https://wordpress.stackexchange.com/questions/43549/count-user-posts-by-user-id-post-type-and-post-status

谢谢

于 2012-12-28T10:24:05.577 回答
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 中传递任何参数

于 2012-12-28T10:39:36.690 回答