I am trying to get the total value of a numerical custom field (‘wpb_post_views_count’) for posts on our website in a loop that is run for each author.

So for each author we should be able to fetch the sum of ‘wpb_post_views_count’ for all posts in a loop of posts for each author.

I have written the following code to do this but it does not work properly. I find values being repeated for each and incorrect for each author.


$user_args = array( 'role' => 'Administrator', 'exclude' => array(1, 11, 183) );

$user_query = new WP_User_Query( $user_args );

if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {    
        $pvc_sum = 0;  
        $author = get_userdata( $user->ID );
        $author_name = $author->user_nicename;
        $args = array( 'posts_per_page' => 999, 'post_status' => 'publish', 'post_type' => 'post', 'author_name' => $author_name );
        $queried_posts = new WP_Query( $args );            
            foreach ( $queried_posts as $post ) {
                $post_id = $post->ID;
                $pvc_sum+= get_post_field( 'wpb_post_views_count', $post_id );
        echo '<p>' . $user->display_name . ' : ' . $pvc_sum . '</p>';           
} } else { }


I am struggling to understand why this is not returning the information it should.

If it helps to think of answer the question, the custom field is a counter of page views for each post.

Any help would be much appreciated. Many thanks.

Read more here: Getting sum of custom field values in WordPress loop


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: