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」の 2 つのカスタム投稿タイプがある場合、「foo_type」のカウントだけでなく、両方のカウントを返すようにこのコードを変更するにはどうすればよいですか?

4

3 に答える 3

1

クエリに 2 番目の 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')); ?>

以下のURLをご覧ください。

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 に答える