Show total author's post views by posts post_meta

I’m searching the web on the last 3 hours without success.

I have a website where authors can publish posts, and posts views are tracking using postmeta “post_views_count”.

I’m using this code and works, but show me the count only for the first 5 posts and not for all author posts. This is the code?

global $wp_query;

$author_id = get_current_user_id();

$author_posts = get_posts( array('author' => $author_id) );

$counter = 0; // needed to collect the total sum of views

foreach ( $author_posts as $post ) {

    $views = absint( get_post_meta( $post->ID, 'post_views_count', true ) );

    var_dump($views);

    $counter += $views;
}
echo "{$counter}";

What is wrong? Why show me the count of only 5 posts?
Thanks a lot

Solutions Collecting From Web of "Show total author's post views by posts post_meta"

It’s showing you the first 5 posts because that’s how many posts are on page 1, and you never told it how many posts per page to load, so it used the default posts per page you set under settings.

You’ll want to modify the get_posts call to have the posts_per_page parameter.

However, I will note the following problems:

  • get_posts doesn’t cache the way WP_Query does, switching to directly using WP_Query would be more efficient
  • Storing view counts inside post meta is incredibly innefficient, and slows down page loads
  • Your statistics are unreliable, as you now have race conditions whenever more than one person visits a page, which can lead to deflated values ( your page view updates aren’t atomic operation )
  • It’s no longer possible to cache your pages, and any attempt to cache pages will ruin your stats
  • Instead of echo "{$counter}"; you should just use echo $counter;
  • You’ll almost certainly want to save the view count and cache it, WordPress already maintains post counts for terms categories and post types, page views in post meta is even more expensive
  • Don’t declare stuff you’re never going to use, I’m looking at global $wp_query;

Instead, consider using an existing stats package, such as the Google Analytics API, Jetpack stats, or a metric such as comment counts, twitter retweets or fb shares