Website construction

Total number of articles browsed by WordPress

Jager · December 31 · 2013 3862 times read

Most WordPress will install the wp postviews plug-in to record article views, which is a very practical plug-in. However, it does not provide the function of calculating the total number of article views. To make up for this shortcoming, we can DIY a function of calculating the total number of article views on the basis of plug-ins.

The implementation is very simple, and articles have been shared on the network. The code is as follows:

 //Total browses function lo_all_view() { global $wpdb; $count=0; $views= $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key='views'"); foreach($views as $key=>$value) { $meta_value=$value->meta_value; if($meta_value!=' '){ $count+=(int)$meta_value; } } return $count; }

The principle of this code is to first query all the qualified meta fields, and then do the traversal operation to get the final total number of views, which is tedious.

So I rewrote a function with better performance, especially for websites with a large number of articles. The code is as follows:

 /** *WordPress gets the total number of article views Optimized version By Zhang Ge Blog *Article address: https://zhang.ge/551.html *Please keep the original source for reprinting, thank you for your cooperation! */ function lo_all_view(){ global $wpdb; $count =  $wpdb->get_var("SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key='views'"); return $count; }

The implementation is simpler. You can directly use the sum method of MySQL to calculate the total number of views.

The usage is the same as the above code:

1. Add this function to the WordPress theme function template file functions.php( Note: If a function with the same name has been added before, please delete it first, otherwise a conflict will occur and the website will report an error!

2. To display the total number of views, add the following code:

 <? php echo lo_all_view(); ?>

Well, the sharing of this article is over. I hope it will be helpful to you.

3 responses
  1. Jakehu 2020-12-9 · 15:09

    The total number of views is usually large. How to automatically convert to 1K when the number exceeds 1000, and to 1W when the number reaches 10000? How to add this judgment?
    if ($num >= 100000) {
    $num = '10w+';
    } elseif ($num >= 10000) {
    $num = round($num / 10000 * 100) / 100 .' w';
    } elseif($num >= 1000) {
    $num = round($num / 1000 * 100) / 100 . ' k';
    } else {
    $num = $num;
    }
    return $num;

  2. Jakehu 2020-12-9 · 15:26

    It has been solved.

  3. Where the total number of views needs to be displayed 2020-12-27 · 10:48

    Can you be more specific where you need to display the total number of views? Wordpress