0

I am having a website which is currently consist of multiple authors, Currently my website is having a module to count the total no. of views and i am storing this value in post meta as a cv_posts_views.

I wanted to achieve a functionality on the author page. whenever someone visit an author page it will show the average of post views per post for that author.

e.g.

Author name : xyz
total posts : 100
total likes of all posts : 20000
average likes per post : ???

I don't know how to loop through all the posts and getting the value from the post meta table then add them and then calculate the average on the basis of total posts. How can i achieve this.

2

You can use count_user_posts() function to get the number of total posts for specific author. With looping through all posts by the specific author, you can get the number of likes on each post and store it/add it in one variable. Here is a function for that.

<?php 
    function avg_num_of_likes() {
        $author = get_user_by( 'id', get_query_var( 'author' ) );
        $author_id = $author->ID;
        $number_of_posts = count_user_posts( $author_id );
        $sumLikes = 0;
        $avgLikes = 0;

        $args = array(
            'author'    => $author_id
        );
        $author_query = new WP_Query( $args );

        if( $author_query->have_posts() ) : while( $author_query->have_posts() ) : $author_query->the_post();
            $sumLikes += get_post_meta( get_the_ID(), 'cv_posts_view', true );
        endwhile; endif;
        wp_reset_postdata();

        $avgLikes = $number_of_posts / $sumLikes;

        return $avgLikes;
    }
    ?>

Call avg_num_of_likes() in the place where you want the average number of likes to be displayed on the author's page.

@Harman Preet You can use an additional function for that. And change $avgLikes = $number_of_posts / $sumLikes; to $avgLikes = custom_number_format( $number_of_posts / $sumLikes );.

function custom_number_format($n, $precision = 1) {
    if($n < 1000 ) {
        $n_format = number_format($n);
    }
    else if ($n < 1000000) {
        // Anything less than a million
        $n_format = number_format($n / 1000, $precision) . 'K';
    } else if ($n < 1000000000) {
        // Anything less than a billion
        $n_format = number_format($n / 1000000, $precision) . 'M';
    } else {
        // At least a billion
        $n_format = number_format($n / 1000000000, $precision) . 'B';
    }

    return $n_format;
}

Ref: https://stackoverflow.com/questions/4371059/shorten-long-numbers-to-k-m-b

  • Thanks @Boris Kuzmanov it works. Another query is how can i add annotation in the end of the count e.g. like if the average is 1000 then it should display as 1K and so on for other no. – Harman Preet Mar 13 '15 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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