PluginProbe
WP-PostViews / 1.78
WP-PostViews v1.78
2.0.1 2.0.0 1.01 1.02 1.10 1.11 1.20 1.30 1.31 1.40 1.50 1.66 1.67 1.68 1.69 1.70 1.71 1.72 1.73 1.74 1.75 1.76 1.76.1 1.77 1.78 All 29 releases
wp-postviews / wp-postviews.php

wp-postviews.php in WP-PostViews 1.78, at wp-postviews.php

1,057 lines 38.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Plugin Name: WP-PostViews
4 Plugin URI: https://lesterchan.net/portfolio/programming/php/
5 Description: Enables you to display how many times a post/page had been viewed.
6 Version: 1.78
7 Author: Lester 'GaMerZ' Chan
8 Author URI: https://lesterchan.net
9 Text Domain: wp-postviews
10 */
11
12
13 /*
14 Copyright 2025 Lester Chan (email : lesterchan@gmail.com)
15
16 This program is free software; you can redistribute it and/or modify
17 it under the terms of the GNU General Public License as published by
18 the Free Software Foundation; either version 2 of the License, or
19 (at your option) any later version.
20
21 This program is distributed in the hope that it will be useful,
22 but WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 GNU General Public License for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with this program; if not, write to the Free Software
28 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 */
30
31 ### WP-PostViews Version
32 define( 'WP_POSTVIEWS_VERSION', '1.78' );
33
34 ### Create Text Domain For Translations
35 add_action( 'plugins_loaded', 'postviews_textdomain' );
36 function postviews_textdomain() {
37 load_plugin_textdomain( 'wp-postviews', false, dirname( plugin_basename( __FILE__ ) ) );
38 }
39
40
41 ### Function: Post Views Option Menu
42 add_action('admin_menu', 'postviews_menu');
43 function postviews_menu() {
44 if (function_exists('add_options_page')) {
45 add_options_page(__('PostViews', 'wp-postviews'), __('PostViews', 'wp-postviews'), 'manage_options', 'wp-postviews/postviews-options.php') ;
46 }
47 }
48
49
50 ### Function: Calculate Post Views
51 add_action( 'wp_head', 'process_postviews' );
52 function process_postviews() {
53 global $user_ID, $post;
54 if ( is_int( $post ) ) {
55 $post = get_post( $post );
56 }
57 if ( ! wp_is_post_revision( $post ) && ! is_preview() ) {
58 if ( is_single() || is_page() ) {
59 $id = (int) $post->ID;
60 $views_options = get_option( 'views_options' );
61 if ( !$post_views = get_post_meta( $post->ID, 'views', true ) ) {
62 $post_views = 0;
63 }
64 $should_count = false;
65 switch( (int) $views_options['count'] ) {
66 case 0:
67 $should_count = true;
68 break;
69 case 1:
70 if( empty( $_COOKIE[ USER_COOKIE ] ) && (int) $user_ID === 0 ) {
71 $should_count = true;
72 }
73 break;
74 case 2:
75 if( (int) $user_ID > 0 ) {
76 $should_count = true;
77 }
78 break;
79 }
80 if ( isset( $views_options['exclude_bots'] ) && (int) $views_options['exclude_bots'] === 1 ) {
81 $bots = array(
82 'Google Bot' => 'google'
83 , 'MSN' => 'msnbot'
84 , 'Alex' => 'ia_archiver'
85 , 'Lycos' => 'lycos'
86 , 'Ask Jeeves' => 'jeeves'
87 , 'Altavista' => 'scooter'
88 , 'AllTheWeb' => 'fast-webcrawler'
89 , 'Inktomi' => 'slurp@inktomi'
90 , 'Turnitin.com' => 'turnitinbot'
91 , 'Technorati' => 'technorati'
92 , 'Yahoo' => 'yahoo'
93 , 'Findexa' => 'findexa'
94 , 'NextLinks' => 'findlinks'
95 , 'Gais' => 'gaisbo'
96 , 'WiseNut' => 'zyborg'
97 , 'WhoisSource' => 'surveybot'
98 , 'Bloglines' => 'bloglines'
99 , 'BlogSearch' => 'blogsearch'
100 , 'PubSub' => 'pubsub'
101 , 'Syndic8' => 'syndic8'
102 , 'RadioUserland' => 'userland'
103 , 'Gigabot' => 'gigabot'
104 , 'Become.com' => 'become.com'
105 , 'Baidu' => 'baiduspider'
106 , 'so.com' => '360spider'
107 , 'Sogou' => 'spider'
108 , 'soso.com' => 'sosospider'
109 , 'Yandex' => 'yandex'
110 , 'Ahrefs' => 'AhrefsBot'
111 , 'Bing' => 'bingbot'
112 , 'Apple' => 'applebot'
113 , 'GitCrawler' => 'GitCrawlerBot'
114 , 'Bytedance' => 'Bytespider'
115 , 'webmeup' => 'BLEXBot'
116 );
117 $useragent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
118 foreach ( $bots as $name => $lookfor ) {
119 if ( ! empty( $useragent ) && ( false !== stripos( $useragent, $lookfor ) ) ) {
120 $should_count = false;
121 break;
122 }
123 }
124 }
125 $should_count = apply_filters( 'postviews_should_count', $should_count, $id );
126 if( $should_count && ( ( isset( $views_options['use_ajax'] ) && (int) $views_options['use_ajax'] === 0 ) || ( !defined( 'WP_CACHE' ) || !WP_CACHE ) ) ) {
127 update_post_meta( $id, 'views', $post_views + 1 );
128 do_action( 'postviews_increment_views', $post_views + 1 );
129 }
130 }
131 }
132 }
133
134 ### Function: Calculate Post Views With WP_CACHE Enabled
135 add_action('wp_enqueue_scripts', 'wp_postview_cache_count_enqueue');
136 function wp_postview_cache_count_enqueue() {
137 global $user_ID, $post;
138
139 if ( !defined( 'WP_CACHE' ) || !WP_CACHE ) {
140 return;
141 }
142
143 $views_options = get_option( 'views_options' );
144
145 if ( isset( $views_options['use_ajax'] ) && (int) $views_options['use_ajax'] === 0 ) {
146 return;
147 }
148
149 if ( !wp_is_post_revision( $post ) && ( is_single() || is_page() ) ) {
150 $should_count = false;
151 switch( (int) $views_options['count'] ) {
152 case 0:
153 $should_count = true;
154 break;
155 case 1:
156 if ( empty( $_COOKIE[USER_COOKIE] ) && (int) $user_ID === 0) {
157 $should_count = true;
158 }
159 break;
160 case 2:
161 if ( (int) $user_ID > 0 ) {
162 $should_count = true;
163 }
164 break;
165 }
166
167 $should_count = apply_filters( 'postviews_should_count', $should_count, (int) $post->ID );
168 if ( $should_count ) {
169 wp_enqueue_script( 'wp-postviews-cache', plugins_url( 'postviews-cache.js', __FILE__ ), array(), WP_POSTVIEWS_VERSION, true );
170 wp_localize_script( 'wp-postviews-cache', 'viewsCacheL10n', array( 'admin_ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'wp_postviews_nonce' ), 'post_id' => (int) $post->ID ) );
171 }
172 }
173 }
174
175
176 ### Function: Determine If Post Views Should Be Displayed (By: David Potter)
177 function should_views_be_displayed($views_options = null) {
178 if ($views_options == null) {
179 $views_options = get_option('views_options');
180 }
181 $display_option = 0;
182 if (is_home()) {
183 if (array_key_exists('display_home', $views_options)) {
184 $display_option = $views_options['display_home'];
185 }
186 } elseif (is_single()) {
187 if (array_key_exists('display_single', $views_options)) {
188 $display_option = $views_options['display_single'];
189 }
190 } elseif (is_page()) {
191 if (array_key_exists('display_page', $views_options)) {
192 $display_option = $views_options['display_page'];
193 }
194 } elseif (is_archive()) {
195 if (array_key_exists('display_archive', $views_options)) {
196 $display_option = $views_options['display_archive'];
197 }
198 } elseif (is_search()) {
199 if (array_key_exists('display_search', $views_options)) {
200 $display_option = $views_options['display_search'];
201 }
202 } else {
203 if (array_key_exists('display_other', $views_options)) {
204 $display_option = $views_options['display_other'];
205 }
206 }
207 return (($display_option == 0) || (($display_option == 1) && is_user_logged_in()));
208 }
209
210
211 ### Function: Display The Post Views
212 function the_views($display = true, $prefix = '', $postfix = '', $always = false) {
213 $post_views = (int) get_post_meta( get_the_ID(), 'views', true );
214 $views_options = get_option('views_options');
215 if ($always || should_views_be_displayed($views_options)) {
216 $output = $prefix.str_replace( array( '%VIEW_COUNT%', '%VIEW_COUNT_ROUNDED%' ), array( number_format_i18n( $post_views ), postviews_round_number( $post_views) ), stripslashes( $views_options['template'] ) ).$postfix;
217 if($display) {
218 echo apply_filters('the_views', $output);
219 } else {
220 return apply_filters('the_views', $output);
221 }
222 }
223 elseif (!$display) {
224 return '';
225 }
226 }
227
228 ### Function: Short Code For Inserting Views Into Posts
229 add_shortcode( 'views', 'views_shortcode' );
230 function views_shortcode( $atts ) {
231 $attributes = shortcode_atts( array( 'id' => 0 ), $atts );
232 $id = (int) $attributes['id'];
233 if( $id === 0) {
234 $id = get_the_ID();
235 }
236 $views_options = get_option( 'views_options' );
237 $post_views = (int) get_post_meta( $id, 'views', true );
238 $output = str_replace( array( '%VIEW_COUNT%', '%VIEW_COUNT_ROUNDED%' ), array( number_format_i18n( $post_views ), postviews_round_number( $post_views) ), stripslashes( $views_options['template'] ) );
239
240 return apply_filters( 'the_views', $output );
241 }
242
243
244 ### Function: Display Least Viewed Page/Post
245 if ( ! function_exists( 'get_least_viewed' ) ) {
246 function get_least_viewed( $mode = '', $limit = 10, $chars = 0, $display = true ) {
247 $views_options = get_option( 'views_options' );
248 $output = '';
249
250 $least_viewed = new WP_Query( array(
251 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
252 'posts_per_page' => $limit,
253 'orderby' => 'meta_value_num',
254 'order' => 'asc',
255 'meta_key' => 'views',
256 ) );
257 if ( $least_viewed->have_posts() ) {
258 while ( $least_viewed->have_posts() ) {
259 $least_viewed->the_post();
260
261 // Post Views.
262 $post_views = get_post_meta( get_the_ID(), 'views', true );
263
264 // Post Title.
265 $post_title = get_the_title();
266 if ( $chars > 0 ) {
267 $post_title = snippet_text( $post_title, $chars );
268 }
269
270 // Post First Category.
271 $categories = get_the_category();
272 $post_category_id = 0;
273 if ( ! empty( $categories ) ) {
274 $post_category_id = $categories[0]->term_id;
275 }
276
277 $temp = stripslashes( $views_options['most_viewed_template'] );
278 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
279 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
280 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
281 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
282 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
283 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
284 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
285 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
286 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
287 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
288 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
289 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
290 $output .= $temp;
291 }
292
293 wp_reset_postdata();
294 } else {
295 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
296 }
297
298 if( $display ) {
299 echo $output;
300 } else {
301 return $output;
302 }
303 }
304 }
305
306
307 ### Function: Display Most Viewed Page/Post
308 if ( ! function_exists( 'get_most_viewed' ) ) {
309 function get_most_viewed( $mode = '', $limit = 10, $chars = 0, $display = true ) {
310 $views_options = get_option( 'views_options' );
311 $output = '';
312
313 $most_viewed = new WP_Query( array(
314 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
315 'posts_per_page' => $limit,
316 'orderby' => 'meta_value_num',
317 'order' => 'desc',
318 'meta_key' => 'views',
319 ) );
320 if ( $most_viewed->have_posts() ) {
321 while ( $most_viewed->have_posts() ) {
322 $most_viewed->the_post();
323
324 // Post Views.
325 $post_views = get_post_meta( get_the_ID(), 'views', true );
326
327 // Post Title.
328 $post_title = get_the_title();
329 if ( $chars > 0 ) {
330 $post_title = snippet_text( $post_title, $chars );
331 }
332
333 // Post First Category.
334 $categories = get_the_category();
335 $post_category_id = 0;
336 if ( ! empty( $categories ) ) {
337 $post_category_id = $categories[0]->term_id;
338 }
339
340 $temp = stripslashes( $views_options['most_viewed_template'] );
341 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
342 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
343 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
344 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
345 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
346 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
347 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
348 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
349 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
350 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
351 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
352 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
353 $output .= $temp;
354 }
355
356 wp_reset_postdata();
357 } else {
358 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
359 }
360
361 if( $display ) {
362 echo $output;
363 } else {
364 return $output;
365 }
366 }
367 }
368
369
370 ### Function: Display Least Viewed Page/Post By Category ID
371 if ( ! function_exists( 'get_least_viewed_category' ) ) {
372 function get_least_viewed_category( $category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
373 $views_options = get_option( 'views_options' );
374 $output = '';
375
376 $least_viewed = new WP_Query( array(
377 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
378 'posts_per_page' => $limit,
379 'category__in' => (array) $category_id,
380 'orderby' => 'meta_value_num',
381 'order' => 'asc',
382 'meta_key' => 'views',
383 ) );
384 if ( $least_viewed->have_posts() ) {
385 while ( $least_viewed->have_posts() ) {
386 $least_viewed->the_post();
387
388 // Post Views.
389 $post_views = get_post_meta( get_the_ID(), 'views', true );
390
391 // Post Title.
392 $post_title = get_the_title();
393 if ( $chars > 0 ) {
394 $post_title = snippet_text( $post_title, $chars );
395 }
396
397 // Post First Category.
398 $categories = get_the_category();
399 $post_category_id = 0;
400 if ( ! empty( $categories ) ) {
401 $post_category_id = $categories[0]->term_id;
402 }
403
404 $temp = stripslashes( $views_options['most_viewed_template'] );
405 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
406 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
407 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
408 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
409 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
410 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
411 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
412 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
413 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
414 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
415 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
416 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
417 $output .= $temp;
418 }
419
420 wp_reset_postdata();
421 } else {
422 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
423 }
424
425 if($display) {
426 echo $output;
427 } else {
428 return $output;
429 }
430 }
431 }
432
433
434 ### Function: Display Most Viewed Page/Post By Category ID
435 if ( ! function_exists( 'get_most_viewed_category' ) ) {
436 function get_most_viewed_category( $category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
437 $views_options = get_option( 'views_options' );
438 $output = '';
439
440 $most_viewed = new WP_Query( array(
441 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
442 'posts_per_page' => $limit,
443 'category__in' => (array) $category_id,
444 'orderby' => 'meta_value_num',
445 'order' => 'desc',
446 'meta_key' => 'views',
447 ) );
448 if ( $most_viewed->have_posts() ) {
449 while ( $most_viewed->have_posts() ) {
450 $most_viewed->the_post();
451
452 // Post Views.
453 $post_views = get_post_meta( get_the_ID(), 'views', true );
454
455 // Post Title.
456 $post_title = get_the_title();
457 if ( $chars > 0 ) {
458 $post_title = snippet_text( $post_title, $chars );
459 }
460
461 // Post First Category.
462 $categories = get_the_category();
463 $post_category_id = 0;
464 if ( ! empty( $categories ) ) {
465 $post_category_id = $categories[0]->term_id;
466 }
467
468 $temp = stripslashes( $views_options['most_viewed_template'] );
469 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
470 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
471 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
472 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
473 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
474 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
475 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
476 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
477 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
478 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
479 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
480 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
481 $output .= $temp;
482 }
483
484 wp_reset_postdata();
485 } else {
486 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
487 }
488
489 if ( $display ) {
490 echo $output;
491 } else {
492 return $output;
493 }
494 }
495 }
496
497 ### Function: Display Least Viewed Page/Post By Tag ID
498 if ( ! function_exists( 'get_least_viewed_tag' ) ) {
499 function get_least_viewed_tag( $tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
500 $views_options = get_option( 'views_options' );
501 $output = '';
502
503 $least_viewed = new WP_Query( array(
504 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
505 'posts_per_page' => $limit,
506 'tag__in' => (array) $tag_id,
507 'orderby' => 'meta_value_num',
508 'order' => 'asc',
509 'meta_key' => 'views',
510 ) );
511 if ( $least_viewed->have_posts() ) {
512 while ( $least_viewed->have_posts() ) {
513 $least_viewed->the_post();
514
515 // Post Views.
516 $post_views = get_post_meta( get_the_ID(), 'views', true );
517
518 // Post Title.
519 $post_title = get_the_title();
520 if ( $chars > 0 ) {
521 $post_title = snippet_text( $post_title, $chars );
522 }
523
524 // Post First Category.
525 $categories = get_the_category();
526 $post_category_id = 0;
527 if ( ! empty( $categories ) ) {
528 $post_category_id = $categories[0]->term_id;
529 }
530
531 $temp = stripslashes( $views_options['most_viewed_template'] );
532 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
533 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
534 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
535 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
536 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
537 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
538 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
539 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
540 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
541 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
542 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
543 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
544 $output .= $temp;
545 }
546
547 wp_reset_postdata();
548 } else {
549 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
550 }
551
552 if ( $display ) {
553 echo $output;
554 } else {
555 return $output;
556 }
557 }
558 }
559
560
561 ### Function: Display Most Viewed Page/Post By Tag ID
562 if ( ! function_exists( 'get_most_viewed_tag' ) ) {
563 function get_most_viewed_tag( $tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
564 $views_options = get_option( 'views_options' );
565 $output = '';
566
567 $most_viewed = new WP_Query( array(
568 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
569 'posts_per_page' => $limit,
570 'tag__in' => (array) $tag_id,
571 'orderby' => 'meta_value_num',
572 'order' => 'desc',
573 'meta_key' => 'views',
574 ) );
575 if ( $most_viewed->have_posts() ) {
576 while ( $most_viewed->have_posts() ) {
577 $most_viewed->the_post();
578
579 // Post Views.
580 $post_views = get_post_meta( get_the_ID(), 'views', true );
581
582 // Post Title.
583 $post_title = get_the_title();
584 if ( $chars > 0 ) {
585 $post_title = snippet_text( $post_title, $chars );
586 }
587
588 // Post First Category.
589 $categories = get_the_category();
590 $post_category_id = 0;
591 if ( ! empty( $categories ) ) {
592 $post_category_id = $categories[0]->term_id;
593 }
594
595 $temp = stripslashes( $views_options['most_viewed_template'] );
596 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
597 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
598 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
599 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
600 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
601 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
602 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
603 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
604 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
605 $temp = str_replace( '%POST_THUMBNAIL_URL%', get_the_post_thumbnail_url( null,'thumbnail',true ), $temp);
606 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
607 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
608 $output .= $temp;
609 }
610
611 wp_reset_postdata();
612 } else {
613 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
614 }
615
616 if($display) {
617 echo $output;
618 } else {
619 return $output;
620 }
621 }
622 }
623
624
625 ### Function: Display Total Views
626 if(!function_exists('get_totalviews')) {
627 function get_totalviews($display = true) {
628 global $wpdb;
629 $total_views = (int) $wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'" );
630 if($display) {
631 echo number_format_i18n($total_views);
632 } else {
633 return $total_views;
634 }
635 }
636 }
637
638
639 ### Function: Snippet Text
640 if(!function_exists('snippet_text')) {
641 function snippet_text($text, $length = 0) {
642 if (defined('MB_OVERLOAD_STRING')) {
643 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
644 if (mb_strlen($text) > $length) {
645 return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
646 } else {
647 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
648 }
649 } else {
650 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
651 if (strlen($text) > $length) {
652 return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
653 } else {
654 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
655 }
656 }
657 }
658 }
659
660
661 ### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
662 function views_fields($content) {
663 global $wpdb;
664 $content .= ", ($wpdb->postmeta.meta_value+0) AS views";
665 return $content;
666 }
667 function views_join($content) {
668 global $wpdb;
669 $content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
670 return $content;
671 }
672 function views_where($content) {
673 global $wpdb;
674 $content .= " AND $wpdb->postmeta.meta_key = 'views'";
675 return $content;
676 }
677 function views_orderby($content) {
678 $orderby = trim(addslashes(get_query_var('v_orderby')));
679 if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
680 $orderby = 'desc';
681 }
682 $content = " views $orderby";
683 return $content;
684 }
685
686
687 ### Function: Add Views Custom Fields
688 add_action('publish_post', 'add_views_fields');
689 add_action('publish_page', 'add_views_fields');
690 function add_views_fields($post_ID) {
691 global $wpdb;
692 if(!wp_is_post_revision($post_ID)) {
693 add_post_meta($post_ID, 'views', 0, true);
694 }
695 }
696
697
698 ### Function: Views Public Variables
699 add_filter('query_vars', 'views_variables');
700 function views_variables($public_query_vars) {
701 $public_query_vars[] = 'v_sortby';
702 $public_query_vars[] = 'v_orderby';
703 return $public_query_vars;
704 }
705
706
707 ### Function: Sort Views Posts
708 add_action('pre_get_posts', 'views_sorting');
709 function views_sorting($local_wp_query) {
710 if($local_wp_query->get('v_sortby') == 'views') {
711 add_filter('posts_fields', 'views_fields');
712 add_filter('posts_join', 'views_join');
713 add_filter('posts_where', 'views_where');
714 add_filter('posts_orderby', 'views_orderby');
715 } else {
716 remove_filter('posts_fields', 'views_fields');
717 remove_filter('posts_join', 'views_join');
718 remove_filter('posts_where', 'views_where');
719 remove_filter('posts_orderby', 'views_orderby');
720 }
721 }
722
723
724 ### Function: Plug Into WP-Stats
725 add_action( 'plugins_loaded', 'postviews_wp_stats' );
726 function postviews_wp_stats() {
727 add_filter( 'wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats' );
728 add_filter( 'wp_stats_page_admin_most', 'postviews_page_admin_most_stats' );
729 add_filter( 'wp_stats_page_plugins', 'postviews_page_general_stats' );
730 add_filter( 'wp_stats_page_most', 'postviews_page_most_stats' );
731 }
732
733
734 ### Function: Add WP-PostViews General Stats To WP-Stats Page Options
735 function postviews_page_admin_general_stats($content) {
736 $stats_display = get_option('stats_display');
737 if ( (int) $stats_display['views'] === 1 ) {
738 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_views" value="views" checked="checked" />&nbsp;&nbsp;<label for="wpstats_views">'.__('WP-PostViews', 'wp-postviews').'</label><br />'."\n";
739 } else {
740 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_views" value="views" />&nbsp;&nbsp;<label for="wpstats_views">'.__('WP-PostViews', 'wp-postviews').'</label><br />'."\n";
741 }
742 return $content;
743 }
744
745
746 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page Options
747 function postviews_page_admin_most_stats($content) {
748 $stats_display = get_option('stats_display');
749 $stats_mostlimit = (int) get_option('stats_mostlimit');
750 if ( (int) $stats_display['viewed_most_post'] === 1 ) {
751 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_viewed_most_post" value="viewed_most_post" checked="checked" />&nbsp;&nbsp;<label for="wpstats_viewed_most_post">'.sprintf(_n('%s Most Viewed Post', '%s Most Viewed Posts', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</label><br />'."\n";
752 } else {
753 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_viewed_most_post" value="viewed_most_post" />&nbsp;&nbsp;<label for="wpstats_viewed_most_post">'.sprintf(_n('%s Most Viewed Post', '%s Most Viewed Posts', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</label><br />'."\n";
754 }
755 if ( (int) $stats_display['viewed_most_page'] === 1 ) {
756 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_viewed_most_page" value="viewed_most_page" checked="checked" />&nbsp;&nbsp;<label for="wpstats_viewed_most_page">'.sprintf(_n('%s Most Viewed Page', '%s Most Viewed Pages', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</label><br />'."\n";
757 } else {
758 $content .= '<input type="checkbox" name="stats_display[]" id="wpstats_viewed_most_page" value="viewed_most_page" />&nbsp;&nbsp;<label for="wpstats_viewed_most_page">'.sprintf(_n('%s Most Viewed Page', '%s Most Viewed Pages', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</label><br />'."\n";
759 }
760 return $content;
761 }
762
763
764 ### Function: Add WP-PostViews General Stats To WP-Stats Page
765 function postviews_page_general_stats($content) {
766 $stats_display = get_option('stats_display');
767 if ( (int) $stats_display['views'] === 1 ) {
768 $content .= '<p><strong>'.__('WP-PostViews', 'wp-postviews').'</strong></p>'."\n";
769 $content .= '<ul>'."\n";
770 $content .= '<li>'.sprintf(_n('<strong>%s</strong> view was generated.', '<strong>%s</strong> views were generated.', get_totalviews(false), 'wp-postviews'), number_format_i18n(get_totalviews(false))).'</li>'."\n";
771 $content .= '</ul>'."\n";
772 }
773 return $content;
774 }
775
776
777 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page
778 function postviews_page_most_stats($content) {
779 $stats_display = get_option('stats_display');
780 $stats_mostlimit = (int) get_option('stats_mostlimit');
781 if ( (int) $stats_display['viewed_most_post'] === 1 ) {
782 $content .= '<p><strong>'.sprintf(_n('%s Most Viewed Post', '%s Most Viewed Posts', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</strong></p>'."\n";
783 $content .= '<ul>'."\n";
784 $content .= get_most_viewed('post', $stats_mostlimit, 0, false);
785 $content .= '</ul>'."\n";
786 }
787 if($stats_display['viewed_most_page'] == 1) {
788 $content .= '<p><strong>'.sprintf(_n('%s Most Viewed Page', '%s Most Viewed Pages', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'</strong></p>'."\n";
789 $content .= '<ul>'."\n";
790 $content .= get_most_viewed('page', $stats_mostlimit, 0, false);
791 $content .= '</ul>'."\n";
792 }
793 return $content;
794 }
795
796
797 ### Function: Increment Post Views
798 add_action( 'wp_ajax_postviews', 'increment_views' );
799 add_action( 'wp_ajax_nopriv_postviews', 'increment_views' );
800 function increment_views() {
801 $security = check_ajax_referer( 'wp_postviews_nonce', 'nonce' );
802
803 if ( false === $security ) {
804 wp_send_json_error();
805 wp_die();
806 }
807
808 if ( ! isset( $_POST['postviews_id'] ) || empty( $_POST['postviews_id'] ) ) {
809 return;
810 }
811
812 if ( !defined( 'WP_CACHE' ) || ! WP_CACHE ) {
813 return;
814 }
815
816 $views_options = get_option( 'views_options' );
817
818 if ( isset( $views_options['use_ajax'] ) && (int) $views_options['use_ajax'] === 0 ) {
819 return;
820 }
821
822 $post_id = (int) sanitize_key( $_POST['postviews_id'] );
823 if( $post_id > 0 ) {
824 $post_views = (int) get_post_meta( $post_id, 'views', true );
825 $post_views = $post_views + 1;
826 update_post_meta( $post_id, 'views', $post_views );
827 do_action( 'postviews_increment_views_ajax', $post_views );
828 wp_send_json_success( [ 'views' => $post_views ] );
829 exit();
830 }
831 }
832
833 ### Function Show Post Views Column in WP-Admin
834 add_action('manage_posts_custom_column', 'add_postviews_column_content');
835 add_filter('manage_posts_columns', 'add_postviews_column');
836 add_action('manage_pages_custom_column', 'add_postviews_column_content');
837 add_filter('manage_pages_columns', 'add_postviews_column');
838 function add_postviews_column($defaults) {
839 $defaults['views'] = __( 'Views', 'wp-postviews' );
840 return $defaults;
841 }
842
843
844 ### Functions Fill In The Views Count
845 function add_postviews_column_content($column_name) {
846 if ($column_name === 'views' ) {
847 if ( function_exists('the_views' ) ) {
848 the_views( true, '', '', true );
849 }
850 }
851 }
852
853
854 ### Function Sort Columns
855 add_filter( 'manage_edit-post_sortable_columns', 'sort_postviews_column');
856 add_filter( 'manage_edit-page_sortable_columns', 'sort_postviews_column' );
857 function sort_postviews_column( $defaults ) {
858 $defaults['views'] = 'views';
859 return $defaults;
860 }
861 add_action('pre_get_posts', 'sort_postviews');
862 function sort_postviews($query) {
863 if ( ! is_admin() ) {
864 return;
865 }
866 $orderby = $query->get('orderby');
867 if ( 'views' === $orderby ) {
868 $query->set( 'meta_key', 'views' );
869 $query->set( 'orderby', 'meta_value_num' );
870 }
871 }
872
873 ### Function: Round Numbers To K (Thousand), M (Million) or B (Billion)
874 function postviews_round_number( $number, $min_value = 1000, $decimal = 1 ) {
875 if( $number < $min_value ) {
876 return number_format_i18n( $number );
877 }
878 $alphabets = array( 1000000000 => 'B', 1000000 => 'M', 1000 => 'K' );
879 foreach( $alphabets as $key => $value )
880 if( $number >= $key ) {
881 return round( $number / $key, $decimal ) . '' . $value;
882 }
883 }
884
885
886 ### Class: WP-PostViews Widget
887 class WP_Widget_PostViews extends WP_Widget {
888 // Constructor
889 public function __construct() {
890 $widget_ops = array('description' => __('WP-PostViews views statistics', 'wp-postviews'));
891 parent::__construct('views', __('Views', 'wp-postviews'), $widget_ops);
892 }
893
894 // Display Widget
895 public function widget($args, $instance) {
896 $title = apply_filters('widget_title', esc_attr($instance['title']));
897 $type = esc_attr($instance['type']);
898 $mode = esc_attr($instance['mode']);
899 $limit = (int) $instance['limit'];
900 $chars = (int) $instance['chars'];
901 $cat_ids = explode(',', esc_attr($instance['cat_ids']));
902 echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title'];
903 echo '<ul>'."\n";
904 switch($type) {
905 case 'least_viewed':
906 get_least_viewed($mode, $limit, $chars);
907 break;
908 case 'most_viewed':
909 get_most_viewed($mode, $limit, $chars);
910 break;
911 case 'most_viewed_category':
912 get_most_viewed_category($cat_ids, $mode, $limit, $chars);
913 break;
914 case 'least_viewed_category':
915 get_least_viewed_category($cat_ids, $mode, $limit, $chars);
916 break;
917 }
918 echo '</ul>'."\n";
919 echo $args['after_widget'];
920 }
921
922 // When Widget Control Form Is Posted
923 public function update($new_instance, $old_instance) {
924 if (!isset($new_instance['submit'])) {
925 return false;
926 }
927 $instance = $old_instance;
928 $instance['title'] = strip_tags($new_instance['title']);
929 $instance['type'] = strip_tags($new_instance['type']);
930 $instance['mode'] = strip_tags($new_instance['mode']);
931 $instance['limit'] = (int) $new_instance['limit'];
932 $instance['chars'] = (int) $new_instance['chars'];
933 $instance['cat_ids'] = strip_tags($new_instance['cat_ids']);
934 return $instance;
935 }
936
937 // DIsplay Widget Control Form
938 public function form($instance) {
939 $instance = wp_parse_args((array) $instance, array('title' => __('Views', 'wp-postviews'), 'type' => 'most_viewed', 'mode' => '', 'limit' => 10, 'chars' => 200, 'cat_ids' => '0'));
940 $title = esc_attr($instance['title']);
941 $type = esc_attr($instance['type']);
942 $mode = trim(esc_attr($instance['mode']));
943 $limit = (int) $instance['limit'];
944 $chars = (int) $instance['chars'];
945 $cat_ids = esc_attr($instance['cat_ids']);
946 $post_types = get_post_types(array(
947 'public' => true
948 ));
949 ?>
950 <p>
951 <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'wp-postviews'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label>
952 </p>
953 <p>
954 <label for="<?php echo $this->get_field_id('type'); ?>"><?php _e('Statistics Type:', 'wp-postviews'); ?>
955 <select name="<?php echo $this->get_field_name('type'); ?>" id="<?php echo $this->get_field_id('type'); ?>" class="widefat">
956 <option value="least_viewed"<?php selected('least_viewed', $type); ?>><?php _e('Least Viewed', 'wp-postviews'); ?></option>
957 <option value="least_viewed_category"<?php selected('least_viewed_category', $type); ?>><?php _e('Least Viewed By Category', 'wp-postviews'); ?></option>
958 <optgroup>&nbsp;</optgroup>
959 <option value="most_viewed"<?php selected('most_viewed', $type); ?>><?php _e('Most Viewed', 'wp-postviews'); ?></option>
960 <option value="most_viewed_category"<?php selected('most_viewed_category', $type); ?>><?php _e('Most Viewed By Category', 'wp-postviews'); ?></option>
961 </select>
962 </label>
963 </p>
964 <p>
965 <label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Include Views From:', 'wp-postviews'); ?>
966 <select name="<?php echo $this->get_field_name('mode'); ?>" id="<?php echo $this->get_field_id('mode'); ?>" class="widefat">
967 <option value=""<?php selected('', $mode); ?>><?php _e('All', 'wp-postviews'); ?></option>
968 <?php if($post_types > 0): ?>
969 <?php foreach($post_types as $post_type): ?>
970 <option value="<?php echo $post_type; ?>"<?php selected($post_type, $mode); ?>><?php printf(__('%s Only', 'wp-postviews'), ucfirst($post_type)); ?></option>
971 <?php endforeach; ?>
972 <?php endif; ?>
973 </select>
974 </label>
975 </p>
976 <p>
977 <label for="<?php echo $this->get_field_id('limit'); ?>"><?php _e('No. Of Records To Show:', 'wp-postviews'); ?> <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" /></label>
978 </p>
979 <p>
980 <label for="<?php echo $this->get_field_id('chars'); ?>"><?php _e('Maximum Post Title Length (Characters):', 'wp-postviews'); ?> <input class="widefat" id="<?php echo $this->get_field_id('chars'); ?>" name="<?php echo $this->get_field_name('chars'); ?>" type="text" value="<?php echo $chars; ?>" /></label><br />
981 <small><?php _e('<strong>0</strong> to disable.', 'wp-postviews'); ?></small>
982 </p>
983 <p>
984 <label for="<?php echo $this->get_field_id('cat_ids'); ?>"><?php _e('Category IDs:', 'wp-postviews'); ?> <span style="color: red;">*</span> <input class="widefat" id="<?php echo $this->get_field_id('cat_ids'); ?>" name="<?php echo $this->get_field_name('cat_ids'); ?>" type="text" value="<?php echo $cat_ids; ?>" /></label><br />
985 <small><?php _e('Separate mutiple categories with commas.', 'wp-postviews'); ?></small>
986 </p>
987 <p style="color: red;">
988 <small><?php _e('* If you are not using any category statistics, you can ignore it.', 'wp-postviews'); ?></small>
989 <p>
990 <input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
991 <?php
992 }
993 }
994
995
996 ### Function: Init WP-PostViews Widget
997 add_action( 'widgets_init', 'widget_views_init' );
998 function widget_views_init() {
999 register_widget( 'WP_Widget_PostViews' );
1000 }
1001
1002
1003 ### Function: Post Views Options
1004 register_activation_hook( __FILE__, 'views_activation' );
1005 function views_activation( $network_wide ) {
1006 // Add Options
1007 $option_name = 'views_options';
1008 $option = array(
1009 'count' => 1,
1010 'exclude_bots' => 0,
1011 'display_home' => 0,
1012 'display_single' => 0,
1013 'display_page' => 0,
1014 'display_archive' => 0,
1015 'display_search' => 0,
1016 'display_other' => 0,
1017 'use_ajax' => 1,
1018 'template' => __( '%VIEW_COUNT% views', 'wp-postviews' ),
1019 'most_viewed_template' => '<li><a href="%POST_URL%" title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% '.__('views', 'wp-postviews').'</li>'
1020 );
1021
1022 if ( is_multisite() && $network_wide ) {
1023 $ms_sites = function_exists( 'get_sites' ) ? get_sites() : wp_get_sites();
1024
1025 if( 0 < count( $ms_sites ) ) {
1026 foreach ( $ms_sites as $ms_site ) {
1027 $blog_id = class_exists( 'WP_Site' ) ? $ms_site->blog_id : $ms_site['blog_id'];
1028 switch_to_blog( $blog_id );
1029 add_option( $option_name, $option );
1030 restore_current_blog();
1031 }
1032 }
1033 } else {
1034 add_option( $option_name, $option );
1035 }
1036 }
1037
1038 ### Function: Parse View Options
1039 function views_options_parse( $key ) {
1040 return ! empty( $_POST[ $key ] ) ? $_POST[ $key ] : null;
1041 }
1042
1043
1044 ### Function: Register views meta field to use it in REST API
1045 add_action('rest_api_init', 'register_rest_views_field');
1046 function register_rest_views_field(){
1047 register_rest_field('post', 'views', array(
1048 'get_callback' => function ($post) {
1049 if (!$post_views = get_post_meta($post['id'], 'views', true)) {
1050 $post_views = 0;
1051 }
1052
1053 return (int) $post_views;
1054 }
1055 ));
1056 }
1057