0

I'm looking to display the total views generated by each author on their author page. I can't find any php code that works. Can anyone help?

I've tried using this code:

<?php
$author_posts = get_posts( array('author' => $current_user->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 ) );
    $counter += $views;
}
echo "{$counter}";
?>

but the number displayed stays on '0'. Am I doing something obvious wrong? Here's one of my author pages: http://fresharsenal.com/author/olipricebates/

Any help greatly appreciated! Also if anyone knows how to show the amount of shares generated that'd be ace

1 Answer 1

1

The $current_user object retrieves the currently signed-in user. What you want is the ID of the author whose page you're viewing. Try this:

global $wp_query;
$author_id = $wp_query->queried_object_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 ) );
    $counter += $views;
}

echo "{$counter}";

Echo out views, to see if there are any:

foreach ( $author_posts as $post ) {

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

    var_dump($views);

    $counter += $views;
}
12

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.