3

I use the following code to count user posts by specific post type:

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 );
}

// Echo Count
echo count_user_posts_by_type( $user_ID, 'reports' );

Looking for an elegant solution to limit posts by dates. For example, last week\month posts.

1 Answer 1

2

The elegant way to get posts out of the database is to use wp_query. It has all the filters you need:

function wpse70323_count_user_posts_by_type( $userid, $post_type, $year, $month, $day ) {
  $query = new WP_Query( array(
    'author'         => $userid,
    'post_type'      => $post_type,
    'date_query'     => array(
       array(
         'year'      => $year,
         'month'     => $month,
         'day'       => $day,
         ),
        ),
    'posts_per_page' => -1,       
    )); 
  $count = $query->post_count;
  return $count;
  }

It's also possible to return ranges of dates, depending on your needs. Read the documentation on wp_query for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.