wp_count_posts, wp_count_terms and wp_count_comments for specific user?

Is there a way for the functions wp_count_posts, wp_count_terms and wp_count_comments to return their results only for a specific user, possibly by using a user’s ID?

I’m making a custom “Right Now” dashboard widget for a custom post type and I need it to show data for the current user only, not for the whole site.

Thanks in advance.


EDIT: In response to @kaiser ‘s comment below, I did the following, but nothing’s happening – the results are the same as when the filter is out (which should not be the case – checked that this user has a different number of published employee post types). It seems that the code inside my function is not even being called at all coz it’s not outputting the test echo statement inside it:

<?php

// employer right now widget
wp_add_dashboard_widget('dashboard_right_now', __('Right Now'), 'employer_dashboard_right_now');
function limit_to_current_user( $where ) {
    global $wpdb, $current_user;
    $current_user_ID = (int) $current_user->ID;

    $new_where = $wpdb->prepare( 
        $where . " AND post_author = %s "
        ,$current_user_ID );

    var_dump($new_where); // not dumping anything, not even string(0) "" and no errors reported whatsoever, even in php_error_log

    return $new_where;
}
function employer_dashboard_right_now() {

    // modify query to limit to current user
    add_filter('posts_where', 'limit_to_current_user');
    // execute queries
    $num_employees = wp_count_posts('employee');
    $num_comm = wp_count_comments();
    // remove filter
    remove_filter('posts_where', 'limit_to_current_user');

    // more code here...

}

?>

1 Answer
1

I ended up writing my own custom code for wp_count_posts() and wp_count_comments() to generate the counts from scratch (through custom wp queries) based on their original code (wp_count_posts() is in wp-includes/post.php and wp_count_comments() is in wp-includes/comment.php). Thanks @kaiser for the excellent effort.

Leave a Comment