PluginProbe
WP-PostViews / 1.77
WP-PostViews v1.77
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.77, at wp-postviews.php

1,051 lines 38.0 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.77
7 Author: Lester 'GaMerZ' Chan
8 Author URI: https://lesterchan.net
9 Text Domain: wp-postviews
10 */
11
12
13 /*
14 Copyright 2023 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.77' );
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_CATEGORY_ID%', $post_category_id, $temp );
288 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
289 $output .= $temp;
290 }
291
292 wp_reset_postdata();
293 } else {
294 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
295 }
296
297 if( $display ) {
298 echo $output;
299 } else {
300 return $output;
301 }
302 }
303 }
304
305
306 ### Function: Display Most Viewed Page/Post
307 if ( ! function_exists( 'get_most_viewed' ) ) {
308 function get_most_viewed( $mode = '', $limit = 10, $chars = 0, $display = true ) {
309 $views_options = get_option( 'views_options' );
310 $output = '';
311
312 $most_viewed = new WP_Query( array(
313 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
314 'posts_per_page' => $limit,
315 'orderby' => 'meta_value_num',
316 'order' => 'desc',
317 'meta_key' => 'views',
318 ) );
319 if ( $most_viewed->have_posts() ) {
320 while ( $most_viewed->have_posts() ) {
321 $most_viewed->the_post();
322
323 // Post Views.
324 $post_views = get_post_meta( get_the_ID(), 'views', true );
325
326 // Post Title.
327 $post_title = get_the_title();
328 if ( $chars > 0 ) {
329 $post_title = snippet_text( $post_title, $chars );
330 }
331
332 // Post First Category.
333 $categories = get_the_category();
334 $post_category_id = 0;
335 if ( ! empty( $categories ) ) {
336 $post_category_id = $categories[0]->term_id;
337 }
338
339 $temp = stripslashes( $views_options['most_viewed_template'] );
340 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
341 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
342 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
343 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
344 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
345 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
346 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
347 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
348 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
349 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
350 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
351 $output .= $temp;
352 }
353
354 wp_reset_postdata();
355 } else {
356 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
357 }
358
359 if( $display ) {
360 echo $output;
361 } else {
362 return $output;
363 }
364 }
365 }
366
367
368 ### Function: Display Least Viewed Page/Post By Category ID
369 if ( ! function_exists( 'get_least_viewed_category' ) ) {
370 function get_least_viewed_category( $category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
371 $views_options = get_option( 'views_options' );
372 $output = '';
373
374 $least_viewed = new WP_Query( array(
375 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
376 'posts_per_page' => $limit,
377 'category__in' => (array) $category_id,
378 'orderby' => 'meta_value_num',
379 'order' => 'asc',
380 'meta_key' => 'views',
381 ) );
382 if ( $least_viewed->have_posts() ) {
383 while ( $least_viewed->have_posts() ) {
384 $least_viewed->the_post();
385
386 // Post Views.
387 $post_views = get_post_meta( get_the_ID(), 'views', true );
388
389 // Post Title.
390 $post_title = get_the_title();
391 if ( $chars > 0 ) {
392 $post_title = snippet_text( $post_title, $chars );
393 }
394
395 // Post First Category.
396 $categories = get_the_category();
397 $post_category_id = 0;
398 if ( ! empty( $categories ) ) {
399 $post_category_id = $categories[0]->term_id;
400 }
401
402 $temp = stripslashes( $views_options['most_viewed_template'] );
403 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
404 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
405 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
406 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
407 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
408 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
409 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
410 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
411 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
412 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
413 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
414 $output .= $temp;
415 }
416
417 wp_reset_postdata();
418 } else {
419 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
420 }
421
422 if($display) {
423 echo $output;
424 } else {
425 return $output;
426 }
427 }
428 }
429
430
431 ### Function: Display Most Viewed Page/Post By Category ID
432 if ( ! function_exists( 'get_most_viewed_category' ) ) {
433 function get_most_viewed_category( $category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
434 $views_options = get_option( 'views_options' );
435 $output = '';
436
437 $most_viewed = new WP_Query( array(
438 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
439 'posts_per_page' => $limit,
440 'category__in' => (array) $category_id,
441 'orderby' => 'meta_value_num',
442 'order' => 'desc',
443 'meta_key' => 'views',
444 ) );
445 if ( $most_viewed->have_posts() ) {
446 while ( $most_viewed->have_posts() ) {
447 $most_viewed->the_post();
448
449 // Post Views.
450 $post_views = get_post_meta( get_the_ID(), 'views', true );
451
452 // Post Title.
453 $post_title = get_the_title();
454 if ( $chars > 0 ) {
455 $post_title = snippet_text( $post_title, $chars );
456 }
457
458 // Post First Category.
459 $categories = get_the_category();
460 $post_category_id = 0;
461 if ( ! empty( $categories ) ) {
462 $post_category_id = $categories[0]->term_id;
463 }
464
465 $temp = stripslashes( $views_options['most_viewed_template'] );
466 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
467 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
468 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
469 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
470 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
471 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
472 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
473 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
474 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
475 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
476 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
477 $output .= $temp;
478 }
479
480 wp_reset_postdata();
481 } else {
482 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
483 }
484
485 if ( $display ) {
486 echo $output;
487 } else {
488 return $output;
489 }
490 }
491 }
492
493 ### Function: Display Least Viewed Page/Post By Tag ID
494 if ( ! function_exists( 'get_least_viewed_tag' ) ) {
495 function get_least_viewed_tag( $tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
496 $views_options = get_option( 'views_options' );
497 $output = '';
498
499 $least_viewed = new WP_Query( array(
500 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
501 'posts_per_page' => $limit,
502 'tag__in' => (array) $tag_id,
503 'orderby' => 'meta_value_num',
504 'order' => 'asc',
505 'meta_key' => 'views',
506 ) );
507 if ( $least_viewed->have_posts() ) {
508 while ( $least_viewed->have_posts() ) {
509 $least_viewed->the_post();
510
511 // Post Views.
512 $post_views = get_post_meta( get_the_ID(), 'views', true );
513
514 // Post Title.
515 $post_title = get_the_title();
516 if ( $chars > 0 ) {
517 $post_title = snippet_text( $post_title, $chars );
518 }
519
520 // Post First Category.
521 $categories = get_the_category();
522 $post_category_id = 0;
523 if ( ! empty( $categories ) ) {
524 $post_category_id = $categories[0]->term_id;
525 }
526
527 $temp = stripslashes( $views_options['most_viewed_template'] );
528 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
529 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
530 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
531 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
532 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
533 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
534 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
535 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
536 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
537 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
538 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
539 $output .= $temp;
540 }
541
542 wp_reset_postdata();
543 } else {
544 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
545 }
546
547 if ( $display ) {
548 echo $output;
549 } else {
550 return $output;
551 }
552 }
553 }
554
555
556 ### Function: Display Most Viewed Page/Post By Tag ID
557 if ( ! function_exists( 'get_most_viewed_tag' ) ) {
558 function get_most_viewed_tag( $tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true ) {
559 $views_options = get_option( 'views_options' );
560 $output = '';
561
562 $most_viewed = new WP_Query( array(
563 'post_type' => ( empty( $mode ) || $mode === 'both' ) ? 'any' : $mode,
564 'posts_per_page' => $limit,
565 'tag__in' => (array) $tag_id,
566 'orderby' => 'meta_value_num',
567 'order' => 'desc',
568 'meta_key' => 'views',
569 ) );
570 if ( $most_viewed->have_posts() ) {
571 while ( $most_viewed->have_posts() ) {
572 $most_viewed->the_post();
573
574 // Post Views.
575 $post_views = get_post_meta( get_the_ID(), 'views', true );
576
577 // Post Title.
578 $post_title = get_the_title();
579 if ( $chars > 0 ) {
580 $post_title = snippet_text( $post_title, $chars );
581 }
582
583 // Post First Category.
584 $categories = get_the_category();
585 $post_category_id = 0;
586 if ( ! empty( $categories ) ) {
587 $post_category_id = $categories[0]->term_id;
588 }
589
590 $temp = stripslashes( $views_options['most_viewed_template'] );
591 $temp = str_replace( '%VIEW_COUNT%', number_format_i18n( $post_views ), $temp );
592 $temp = str_replace( '%VIEW_COUNT_ROUNDED%', postviews_round_number( $post_views ), $temp );
593 $temp = str_replace( '%POST_TITLE%', $post_title, $temp );
594 $temp = str_replace( '%POST_EXCERPT%', get_the_excerpt(), $temp );
595 $temp = str_replace( '%POST_CONTENT%', get_the_content(), $temp );
596 $temp = str_replace( '%POST_URL%', get_permalink(), $temp );
597 $temp = str_replace( '%POST_DATE%', get_the_time( get_option( 'date_format' ) ), $temp );
598 $temp = str_replace( '%POST_TIME%', get_the_time( get_option( 'time_format' ) ), $temp );
599 $temp = str_replace( '%POST_THUMBNAIL%', get_the_post_thumbnail( null,'thumbnail',true ), $temp);
600 $temp = str_replace( '%POST_CATEGORY_ID%', $post_category_id, $temp );
601 $temp = str_replace( '%POST_AUTHOR%', get_the_author(), $temp );
602 $output .= $temp;
603 }
604
605 wp_reset_postdata();
606 } else {
607 $output = '<li>' . __( 'N/A', 'wp-postviews' ) . '</li>' . "\n";
608 }
609
610 if($display) {
611 echo $output;
612 } else {
613 return $output;
614 }
615 }
616 }
617
618
619 ### Function: Display Total Views
620 if(!function_exists('get_totalviews')) {
621 function get_totalviews($display = true) {
622 global $wpdb;
623 $total_views = (int) $wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'" );
624 if($display) {
625 echo number_format_i18n($total_views);
626 } else {
627 return $total_views;
628 }
629 }
630 }
631
632
633 ### Function: Snippet Text
634 if(!function_exists('snippet_text')) {
635 function snippet_text($text, $length = 0) {
636 if (defined('MB_OVERLOAD_STRING')) {
637 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
638 if (mb_strlen($text) > $length) {
639 return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
640 } else {
641 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
642 }
643 } else {
644 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
645 if (strlen($text) > $length) {
646 return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
647 } else {
648 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
649 }
650 }
651 }
652 }
653
654
655 ### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
656 function views_fields($content) {
657 global $wpdb;
658 $content .= ", ($wpdb->postmeta.meta_value+0) AS views";
659 return $content;
660 }
661 function views_join($content) {
662 global $wpdb;
663 $content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
664 return $content;
665 }
666 function views_where($content) {
667 global $wpdb;
668 $content .= " AND $wpdb->postmeta.meta_key = 'views'";
669 return $content;
670 }
671 function views_orderby($content) {
672 $orderby = trim(addslashes(get_query_var('v_orderby')));
673 if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
674 $orderby = 'desc';
675 }
676 $content = " views $orderby";
677 return $content;
678 }
679
680
681 ### Function: Add Views Custom Fields
682 add_action('publish_post', 'add_views_fields');
683 add_action('publish_page', 'add_views_fields');
684 function add_views_fields($post_ID) {
685 global $wpdb;
686 if(!wp_is_post_revision($post_ID)) {
687 add_post_meta($post_ID, 'views', 0, true);
688 }
689 }
690
691
692 ### Function: Views Public Variables
693 add_filter('query_vars', 'views_variables');
694 function views_variables($public_query_vars) {
695 $public_query_vars[] = 'v_sortby';
696 $public_query_vars[] = 'v_orderby';
697 return $public_query_vars;
698 }
699
700
701 ### Function: Sort Views Posts
702 add_action('pre_get_posts', 'views_sorting');
703 function views_sorting($local_wp_query) {
704 if($local_wp_query->get('v_sortby') == 'views') {
705 add_filter('posts_fields', 'views_fields');
706 add_filter('posts_join', 'views_join');
707 add_filter('posts_where', 'views_where');
708 add_filter('posts_orderby', 'views_orderby');
709 } else {
710 remove_filter('posts_fields', 'views_fields');
711 remove_filter('posts_join', 'views_join');
712 remove_filter('posts_where', 'views_where');
713 remove_filter('posts_orderby', 'views_orderby');
714 }
715 }
716
717
718 ### Function: Plug Into WP-Stats
719 add_action( 'plugins_loaded', 'postviews_wp_stats' );
720 function postviews_wp_stats() {
721 add_filter( 'wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats' );
722 add_filter( 'wp_stats_page_admin_most', 'postviews_page_admin_most_stats' );
723 add_filter( 'wp_stats_page_plugins', 'postviews_page_general_stats' );
724 add_filter( 'wp_stats_page_most', 'postviews_page_most_stats' );
725 }
726
727
728 ### Function: Add WP-PostViews General Stats To WP-Stats Page Options
729 function postviews_page_admin_general_stats($content) {
730 $stats_display = get_option('stats_display');
731 if ( (int) $stats_display['views'] === 1 ) {
732 $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";
733 } else {
734 $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";
735 }
736 return $content;
737 }
738
739
740 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page Options
741 function postviews_page_admin_most_stats($content) {
742 $stats_display = get_option('stats_display');
743 $stats_mostlimit = (int) get_option('stats_mostlimit');
744 if ( (int) $stats_display['viewed_most_post'] === 1 ) {
745 $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";
746 } else {
747 $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";
748 }
749 if ( (int) $stats_display['viewed_most_page'] === 1 ) {
750 $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";
751 } else {
752 $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";
753 }
754 return $content;
755 }
756
757
758 ### Function: Add WP-PostViews General Stats To WP-Stats Page
759 function postviews_page_general_stats($content) {
760 $stats_display = get_option('stats_display');
761 if ( (int) $stats_display['views'] === 1 ) {
762 $content .= '<p><strong>'.__('WP-PostViews', 'wp-postviews').'</strong></p>'."\n";
763 $content .= '<ul>'."\n";
764 $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";
765 $content .= '</ul>'."\n";
766 }
767 return $content;
768 }
769
770
771 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page
772 function postviews_page_most_stats($content) {
773 $stats_display = get_option('stats_display');
774 $stats_mostlimit = (int) get_option('stats_mostlimit');
775 if ( (int) $stats_display['viewed_most_post'] === 1 ) {
776 $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";
777 $content .= '<ul>'."\n";
778 $content .= get_most_viewed('post', $stats_mostlimit, 0, false);
779 $content .= '</ul>'."\n";
780 }
781 if($stats_display['viewed_most_page'] == 1) {
782 $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";
783 $content .= '<ul>'."\n";
784 $content .= get_most_viewed('page', $stats_mostlimit, 0, false);
785 $content .= '</ul>'."\n";
786 }
787 return $content;
788 }
789
790
791 ### Function: Increment Post Views
792 add_action( 'wp_ajax_postviews', 'increment_views' );
793 add_action( 'wp_ajax_nopriv_postviews', 'increment_views' );
794 function increment_views() {
795 $security = check_ajax_referer( 'wp_postviews_nonce', 'nonce' );
796
797 if ( false === $security ) {
798 wp_send_json_error();
799 wp_die();
800 }
801
802 if ( ! isset( $_POST['postviews_id'] ) || empty( $_POST['postviews_id'] ) ) {
803 return;
804 }
805
806 if ( !defined( 'WP_CACHE' ) || ! WP_CACHE ) {
807 return;
808 }
809
810 $views_options = get_option( 'views_options' );
811
812 if ( isset( $views_options['use_ajax'] ) && (int) $views_options['use_ajax'] === 0 ) {
813 return;
814 }
815
816 $post_id = (int) sanitize_key( $_POST['postviews_id'] );
817 if( $post_id > 0 ) {
818 $post_views = (int) get_post_meta( $post_id, 'views', true );
819 $post_views = $post_views + 1;
820 update_post_meta( $post_id, 'views', $post_views );
821 do_action( 'postviews_increment_views_ajax', $post_views );
822 wp_send_json_success( [ 'views' => $post_views ] );
823 exit();
824 }
825 }
826
827 ### Function Show Post Views Column in WP-Admin
828 add_action('manage_posts_custom_column', 'add_postviews_column_content');
829 add_filter('manage_posts_columns', 'add_postviews_column');
830 add_action('manage_pages_custom_column', 'add_postviews_column_content');
831 add_filter('manage_pages_columns', 'add_postviews_column');
832 function add_postviews_column($defaults) {
833 $defaults['views'] = __( 'Views', 'wp-postviews' );
834 return $defaults;
835 }
836
837
838 ### Functions Fill In The Views Count
839 function add_postviews_column_content($column_name) {
840 if ($column_name === 'views' ) {
841 if ( function_exists('the_views' ) ) {
842 the_views( true, '', '', true );
843 }
844 }
845 }
846
847
848 ### Function Sort Columns
849 add_filter( 'manage_edit-post_sortable_columns', 'sort_postviews_column');
850 add_filter( 'manage_edit-page_sortable_columns', 'sort_postviews_column' );
851 function sort_postviews_column( $defaults ) {
852 $defaults['views'] = 'views';
853 return $defaults;
854 }
855 add_action('pre_get_posts', 'sort_postviews');
856 function sort_postviews($query) {
857 if ( ! is_admin() ) {
858 return;
859 }
860 $orderby = $query->get('orderby');
861 if ( 'views' === $orderby ) {
862 $query->set( 'meta_key', 'views' );
863 $query->set( 'orderby', 'meta_value_num' );
864 }
865 }
866
867 ### Function: Round Numbers To K (Thousand), M (Million) or B (Billion)
868 function postviews_round_number( $number, $min_value = 1000, $decimal = 1 ) {
869 if( $number < $min_value ) {
870 return number_format_i18n( $number );
871 }
872 $alphabets = array( 1000000000 => 'B', 1000000 => 'M', 1000 => 'K' );
873 foreach( $alphabets as $key => $value )
874 if( $number >= $key ) {
875 return round( $number / $key, $decimal ) . '' . $value;
876 }
877 }
878
879
880 ### Class: WP-PostViews Widget
881 class WP_Widget_PostViews extends WP_Widget {
882 // Constructor
883 public function __construct() {
884 $widget_ops = array('description' => __('WP-PostViews views statistics', 'wp-postviews'));
885 parent::__construct('views', __('Views', 'wp-postviews'), $widget_ops);
886 }
887
888 // Display Widget
889 public function widget($args, $instance) {
890 $title = apply_filters('widget_title', esc_attr($instance['title']));
891 $type = esc_attr($instance['type']);
892 $mode = esc_attr($instance['mode']);
893 $limit = (int) $instance['limit'];
894 $chars = (int) $instance['chars'];
895 $cat_ids = explode(',', esc_attr($instance['cat_ids']));
896 echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title'];
897 echo '<ul>'."\n";
898 switch($type) {
899 case 'least_viewed':
900 get_least_viewed($mode, $limit, $chars);
901 break;
902 case 'most_viewed':
903 get_most_viewed($mode, $limit, $chars);
904 break;
905 case 'most_viewed_category':
906 get_most_viewed_category($cat_ids, $mode, $limit, $chars);
907 break;
908 case 'least_viewed_category':
909 get_least_viewed_category($cat_ids, $mode, $limit, $chars);
910 break;
911 }
912 echo '</ul>'."\n";
913 echo $args['after_widget'];
914 }
915
916 // When Widget Control Form Is Posted
917 public function update($new_instance, $old_instance) {
918 if (!isset($new_instance['submit'])) {
919 return false;
920 }
921 $instance = $old_instance;
922 $instance['title'] = strip_tags($new_instance['title']);
923 $instance['type'] = strip_tags($new_instance['type']);
924 $instance['mode'] = strip_tags($new_instance['mode']);
925 $instance['limit'] = (int) $new_instance['limit'];
926 $instance['chars'] = (int) $new_instance['chars'];
927 $instance['cat_ids'] = strip_tags($new_instance['cat_ids']);
928 return $instance;
929 }
930
931 // DIsplay Widget Control Form
932 public function form($instance) {
933 $instance = wp_parse_args((array) $instance, array('title' => __('Views', 'wp-postviews'), 'type' => 'most_viewed', 'mode' => '', 'limit' => 10, 'chars' => 200, 'cat_ids' => '0'));
934 $title = esc_attr($instance['title']);
935 $type = esc_attr($instance['type']);
936 $mode = trim(esc_attr($instance['mode']));
937 $limit = (int) $instance['limit'];
938 $chars = (int) $instance['chars'];
939 $cat_ids = esc_attr($instance['cat_ids']);
940 $post_types = get_post_types(array(
941 'public' => true
942 ));
943 ?>
944 <p>
945 <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>
946 </p>
947 <p>
948 <label for="<?php echo $this->get_field_id('type'); ?>"><?php _e('Statistics Type:', 'wp-postviews'); ?>
949 <select name="<?php echo $this->get_field_name('type'); ?>" id="<?php echo $this->get_field_id('type'); ?>" class="widefat">
950 <option value="least_viewed"<?php selected('least_viewed', $type); ?>><?php _e('Least Viewed', 'wp-postviews'); ?></option>
951 <option value="least_viewed_category"<?php selected('least_viewed_category', $type); ?>><?php _e('Least Viewed By Category', 'wp-postviews'); ?></option>
952 <optgroup>&nbsp;</optgroup>
953 <option value="most_viewed"<?php selected('most_viewed', $type); ?>><?php _e('Most Viewed', 'wp-postviews'); ?></option>
954 <option value="most_viewed_category"<?php selected('most_viewed_category', $type); ?>><?php _e('Most Viewed By Category', 'wp-postviews'); ?></option>
955 </select>
956 </label>
957 </p>
958 <p>
959 <label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Include Views From:', 'wp-postviews'); ?>
960 <select name="<?php echo $this->get_field_name('mode'); ?>" id="<?php echo $this->get_field_id('mode'); ?>" class="widefat">
961 <option value=""<?php selected('', $mode); ?>><?php _e('All', 'wp-postviews'); ?></option>
962 <?php if($post_types > 0): ?>
963 <?php foreach($post_types as $post_type): ?>
964 <option value="<?php echo $post_type; ?>"<?php selected($post_type, $mode); ?>><?php printf(__('%s Only', 'wp-postviews'), ucfirst($post_type)); ?></option>
965 <?php endforeach; ?>
966 <?php endif; ?>
967 </select>
968 </label>
969 </p>
970 <p>
971 <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>
972 </p>
973 <p>
974 <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 />
975 <small><?php _e('<strong>0</strong> to disable.', 'wp-postviews'); ?></small>
976 </p>
977 <p>
978 <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 />
979 <small><?php _e('Separate mutiple categories with commas.', 'wp-postviews'); ?></small>
980 </p>
981 <p style="color: red;">
982 <small><?php _e('* If you are not using any category statistics, you can ignore it.', 'wp-postviews'); ?></small>
983 <p>
984 <input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
985 <?php
986 }
987 }
988
989
990 ### Function: Init WP-PostViews Widget
991 add_action( 'widgets_init', 'widget_views_init' );
992 function widget_views_init() {
993 register_widget( 'WP_Widget_PostViews' );
994 }
995
996
997 ### Function: Post Views Options
998 register_activation_hook( __FILE__, 'views_activation' );
999 function views_activation( $network_wide ) {
1000 // Add Options
1001 $option_name = 'views_options';
1002 $option = array(
1003 'count' => 1,
1004 'exclude_bots' => 0,
1005 'display_home' => 0,
1006 'display_single' => 0,
1007 'display_page' => 0,
1008 'display_archive' => 0,
1009 'display_search' => 0,
1010 'display_other' => 0,
1011 'use_ajax' => 1,
1012 'template' => __( '%VIEW_COUNT% views', 'wp-postviews' ),
1013 'most_viewed_template' => '<li><a href="%POST_URL%" title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% '.__('views', 'wp-postviews').'</li>'
1014 );
1015
1016 if ( is_multisite() && $network_wide ) {
1017 $ms_sites = function_exists( 'get_sites' ) ? get_sites() : wp_get_sites();
1018
1019 if( 0 < count( $ms_sites ) ) {
1020 foreach ( $ms_sites as $ms_site ) {
1021 $blog_id = class_exists( 'WP_Site' ) ? $ms_site->blog_id : $ms_site['blog_id'];
1022 switch_to_blog( $blog_id );
1023 add_option( $option_name, $option );
1024 restore_current_blog();
1025 }
1026 }
1027 } else {
1028 add_option( $option_name, $option );
1029 }
1030 }
1031
1032 ### Function: Parse View Options
1033 function views_options_parse( $key ) {
1034 return ! empty( $_POST[ $key ] ) ? $_POST[ $key ] : null;
1035 }
1036
1037
1038 ### Function: Register views meta field to use it in REST API
1039 add_action('rest_api_init', 'register_rest_views_field');
1040 function register_rest_views_field(){
1041 register_rest_field('post', 'views', array(
1042 'get_callback' => function ($post) {
1043 if (!$post_views = get_post_meta($post['id'], 'views', true)) {
1044 $post_views = 0;
1045 }
1046
1047 return (int) $post_views;
1048 }
1049 ));
1050 }
1051