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

987 lines 44.3 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: http://lesterchan.net/portfolio/programming/php/
5 Description: Enables you to display how many times a post/page had been viewed.
6 Version: 1.73
7 Author: Lester 'GaMerZ' Chan
8 Author URI: http://lesterchan.net
9 Text Domain: wp-postviews
10 */
11
12
13 /*
14 Copyright 2015 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
32 ### Create Text Domain For Translations
33 add_action( 'plugins_loaded', 'postviews_textdomain' );
34 function postviews_textdomain() {
35 load_plugin_textdomain( 'wp-postviews', false, dirname( plugin_basename( __FILE__ ) ) );
36 }
37
38
39 ### Function: Post Views Option Menu
40 add_action('admin_menu', 'postviews_menu');
41 function postviews_menu() {
42 if (function_exists('add_options_page')) {
43 add_options_page(__('PostViews', 'wp-postviews'), __('PostViews', 'wp-postviews'), 'manage_options', 'wp-postviews/postviews-options.php') ;
44 }
45 }
46
47
48 ### Function: Calculate Post Views
49 add_action( 'wp_head', 'process_postviews' );
50 function process_postviews() {
51 global $user_ID, $post;
52 if( is_int( $post ) ) {
53 $post = get_post( $post );
54 }
55 if( ! wp_is_post_revision( $post ) && ! is_preview() ) {
56 if( is_single() || is_page() ) {
57 $id = intval( $post->ID );
58 $views_options = get_option( 'views_options' );
59 if ( !$post_views = get_post_meta( $post->ID, 'views', true ) ) {
60 $post_views = 0;
61 }
62 $should_count = false;
63 switch( intval( $views_options['count'] ) ) {
64 case 0:
65 $should_count = true;
66 break;
67 case 1:
68 if(empty( $_COOKIE[USER_COOKIE] ) && intval( $user_ID ) === 0) {
69 $should_count = true;
70 }
71 break;
72 case 2:
73 if( intval( $user_ID ) > 0 ) {
74 $should_count = true;
75 }
76 break;
77 }
78 if( intval( $views_options['exclude_bots'] ) === 1 ) {
79 $bots = array
80 (
81 'Google Bot' => 'googlebot'
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 );
111 $useragent = $_SERVER['HTTP_USER_AGENT'];
112 foreach ( $bots as $name => $lookfor ) {
113 if ( stristr( $useragent, $lookfor ) !== false ) {
114 $should_count = false;
115 break;
116 }
117 }
118 }
119 if( $should_count && ( ( isset( $views_options['use_ajax'] ) && intval( $views_options['use_ajax'] ) === 0 ) || ( !defined( 'WP_CACHE' ) || !WP_CACHE ) ) ) {
120 update_post_meta( $id, 'views', ( $post_views + 1 ) );
121 do_action( 'postviews_increment_views', ( $post_views + 1 ) );
122 }
123 }
124 }
125 }
126
127
128 ### Function: Calculate Post Views With WP_CACHE Enabled
129 add_action('wp_enqueue_scripts', 'wp_postview_cache_count_enqueue');
130 function wp_postview_cache_count_enqueue() {
131 global $user_ID, $post;
132
133 if( !defined( 'WP_CACHE' ) || !WP_CACHE )
134 return;
135
136 $views_options = get_option( 'views_options' );
137
138 if( isset( $views_options['use_ajax'] ) && intval( $views_options['use_ajax'] ) === 0 )
139 return;
140
141 if ( !wp_is_post_revision( $post ) && ( is_single() || is_page() ) ) {
142 $should_count = false;
143 switch( intval( $views_options['count'] ) ) {
144 case 0:
145 $should_count = true;
146 break;
147 case 1:
148 if ( empty( $_COOKIE[USER_COOKIE] ) && intval( $user_ID ) === 0) {
149 $should_count = true;
150 }
151 break;
152 case 2:
153 if ( intval( $user_ID ) > 0 ) {
154 $should_count = true;
155 }
156 break;
157 }
158 if ( $should_count ) {
159 wp_enqueue_script( 'wp-postviews-cache', plugins_url( 'postviews-cache.js', __FILE__ ), array( 'jquery' ), '1.68', true );
160 wp_localize_script( 'wp-postviews-cache', 'viewsCacheL10n', array( 'admin_ajax_url' => admin_url( 'admin-ajax.php' ), 'post_id' => intval( $post->ID ) ) );
161 }
162 }
163 }
164
165
166 ### Function: Determine If Post Views Should Be Displayed (By: David Potter)
167 function should_views_be_displayed($views_options = null) {
168 if ($views_options == null) {
169 $views_options = get_option('views_options');
170 }
171 $display_option = 0;
172 if (is_home()) {
173 if (array_key_exists('display_home', $views_options)) {
174 $display_option = $views_options['display_home'];
175 }
176 } elseif (is_single()) {
177 if (array_key_exists('display_single', $views_options)) {
178 $display_option = $views_options['display_single'];
179 }
180 } elseif (is_page()) {
181 if (array_key_exists('display_page', $views_options)) {
182 $display_option = $views_options['display_page'];
183 }
184 } elseif (is_archive()) {
185 if (array_key_exists('display_archive', $views_options)) {
186 $display_option = $views_options['display_archive'];
187 }
188 } elseif (is_search()) {
189 if (array_key_exists('display_search', $views_options)) {
190 $display_option = $views_options['display_search'];
191 }
192 } else {
193 if (array_key_exists('display_other', $views_options)) {
194 $display_option = $views_options['display_other'];
195 }
196 }
197 return (($display_option == 0) || (($display_option == 1) && is_user_logged_in()));
198 }
199
200
201 ### Function: Display The Post Views
202 function the_views($display = true, $prefix = '', $postfix = '', $always = false) {
203 $post_views = intval( get_post_meta( get_the_ID(), 'views', true ) );
204 $views_options = get_option('views_options');
205 if ($always || should_views_be_displayed($views_options)) {
206 $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;
207 if($display) {
208 echo apply_filters('the_views', $output);
209 } else {
210 return apply_filters('the_views', $output);
211 }
212 }
213 elseif (!$display) {
214 return '';
215 }
216 }
217
218 ### Function: Short Code For Inserting Views Into Posts
219 add_shortcode( 'views', 'views_shortcode' );
220 function views_shortcode( $atts ) {
221 $attributes = shortcode_atts( array( 'id' => 0 ), $atts );
222 $id = intval( $attributes['id'] );
223 if( $id === 0) {
224 $id = get_the_ID();
225 }
226 $views_options = get_option( 'views_options' );
227 $post_views = intval( get_post_meta( $id, 'views', true ) );
228 $output = str_replace( array( '%VIEW_COUNT%', '%VIEW_COUNT_ROUNDED%' ), array( number_format_i18n( $post_views ), postviews_round_number( $post_views) ), stripslashes( $views_options['template'] ) );
229
230 return apply_filters( 'the_views', $output );
231 }
232
233
234 ### Function: Display Least Viewed Page/Post
235 if(!function_exists('get_least_viewed')) {
236 function get_least_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
237 global $wpdb;
238 $views_options = get_option('views_options');
239 $where = '';
240 $temp = '';
241 $output = '';
242 if(!empty($mode) && $mode != 'both') {
243 if(is_array($mode)) {
244 $mode = implode("','",$mode);
245 $where = "post_type IN ('".$mode."')";
246 } else {
247 $where = "post_type = '$mode'";
248 }
249 } else {
250 $where = '1=1';
251 }
252 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views ASC LIMIT $limit");
253 if($most_viewed) {
254 foreach ($most_viewed as $post) {
255 $post_views = intval($post->views);
256 $post_title = get_the_title($post);
257 if($chars > 0) {
258 $post_title = snippet_text($post_title, $chars);
259 }
260 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
261 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
262 $temp = stripslashes($views_options['most_viewed_template']);
263 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
264 $temp = str_replace("%VIEW_COUNT_ROUNDED%", postviews_round_number( $post_views ), $temp);
265 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
266 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
267 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
268 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
269 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
270 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
271 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
272 $output .= $temp;
273 }
274 } else {
275 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
276 }
277 if($display) {
278 echo $output;
279 } else {
280 return $output;
281 }
282 }
283 }
284
285
286 ### Function: Display Most Viewed Page/Post
287 if(!function_exists('get_most_viewed')) {
288 function get_most_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
289 global $wpdb;
290 $views_options = get_option('views_options');
291 $where = '';
292 $temp = '';
293 $output = '';
294 if(!empty($mode) && $mode != 'both') {
295 if(is_array($mode)) {
296 $mode = implode("','",$mode);
297 $where = "post_type IN ('".$mode."')";
298 } else {
299 $where = "post_type = '$mode'";
300 }
301 } else {
302 $where = '1=1';
303 }
304 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date < '".current_time('mysql')."' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
305 if($most_viewed) {
306 foreach ($most_viewed as $post) {
307 $post_views = intval($post->views);
308 $post_title = get_the_title($post);
309 if($chars > 0) {
310 $post_title = snippet_text($post_title, $chars);
311 }
312 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
313 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
314 $temp = stripslashes($views_options['most_viewed_template']);
315 $temp = str_replace("%VIEW_COUNT%", number_format_i18n( $post_views ), $temp);
316 $temp = str_replace("%VIEW_COUNT_ROUNDED%", postviews_round_number( $post_views ), $temp);
317 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
318 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
319 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
320 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
321 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
322 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
323 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
324 $output .= $temp;
325 }
326 } else {
327 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
328 }
329 if($display) {
330 echo $output;
331 } else {
332 return $output;
333 }
334 }
335 }
336
337
338 ### Function: Display Leased Viewed Page/Post By Category ID
339 if(!function_exists('get_least_viewed_category')) {
340 function get_least_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
341 global $wpdb;
342 $views_options = get_option('views_options');
343 $where = '';
344 $temp = '';
345 $output = '';
346 if(is_array($category_id)) {
347 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
348 } else {
349 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
350 }
351 if(!empty($mode) && $mode != 'both') {
352 if(is_array($mode)) {
353 $mode = implode("','",$mode);
354 $where = "post_type IN ('".$mode."')";
355 } else {
356 $where = "post_type = '$mode'";
357 }
358 } else {
359 $where = '1=1';
360 }
361 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE post_date < '".current_time('mysql')."' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $category_sql AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views ASC LIMIT $limit");
362 if($most_viewed) {
363 foreach ($most_viewed as $post) {
364 $post_views = intval($post->views);
365 $post_title = get_the_title($post);
366 if($chars > 0) {
367 $post_title = snippet_text($post_title, $chars);
368 }
369 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
370 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
371 $temp = stripslashes($views_options['most_viewed_template']);
372 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
373 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
374 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
375 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
376 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
377 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
378 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
379 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
380 $output .= $temp;
381 }
382 } else {
383 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
384 }
385 if($display) {
386 echo $output;
387 } else {
388 return $output;
389 }
390 }
391 }
392
393
394 ### Function: Display Most Viewed Page/Post By Category ID
395 if(!function_exists('get_most_viewed_category')) {
396 function get_most_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
397 global $wpdb;
398 $views_options = get_option('views_options');
399 $where = '';
400 $temp = '';
401 $output = '';
402 if(is_array($category_id)) {
403 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
404 } else {
405 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
406 }
407 if(!empty($mode) && $mode != 'both') {
408 if(is_array($mode)) {
409 $mode = implode("','",$mode);
410 $where = "post_type IN ('".$mode."')";
411 } else {
412 $where = "post_type = '$mode'";
413 }
414 } else {
415 $where = '1=1';
416 }
417 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE post_date < '".current_time('mysql')."' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $category_sql AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
418 if($most_viewed) {
419 foreach ($most_viewed as $post) {
420 $post_views = intval($post->views);
421 $post_title = get_the_title($post);
422 if($chars > 0) {
423 $post_title = snippet_text($post_title, $chars);
424 }
425 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
426 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
427 $temp = stripslashes($views_options['most_viewed_template']);
428 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
429 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
430 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
431 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
432 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
433 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
434 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
435 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
436 $output .= $temp;
437 }
438 } else {
439 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
440 }
441 if($display) {
442 echo $output;
443 } else {
444 return $output;
445 }
446 }
447 }
448
449
450 ### Function: Display Most Viewed Page/Post By Tag ID
451 if(!function_exists('get_most_viewed_tag')) {
452 function get_most_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
453 global $wpdb;
454 $views_options = get_option('views_options');
455 $where = '';
456 $temp = '';
457 $output = '';
458 if(is_array($tag_id)) {
459 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
460 } else {
461 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
462 }
463 if(!empty($mode) && $mode != 'both') {
464 if(is_array($mode)) {
465 $mode = implode("','",$mode);
466 $where = "post_type IN ('".$mode."')";
467 } else {
468 $where = "post_type = '$mode'";
469 }
470 } else {
471 $where = '1=1';
472 }
473 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE post_date < '".current_time('mysql')."' AND $wpdb->term_taxonomy.taxonomy = 'post_tag' AND $tag_sql AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
474 if($most_viewed) {
475 foreach ($most_viewed as $post) {
476 $post_views = intval($post->views);
477 $post_title = get_the_title($post);
478 if($chars > 0) {
479 $post_title = snippet_text($post_title, $chars);
480 }
481 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
482 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
483 $temp = stripslashes($views_options['most_viewed_template']);
484 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
485 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
486 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
487 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
488 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
489 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
490 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
491 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
492 $output .= $temp;
493 }
494 } else {
495 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
496 }
497 if($display) {
498 echo $output;
499 } else {
500 return $output;
501 }
502 }
503 }
504
505
506 ### Function: Display Least Viewed Page/Post By Tag ID
507 if(!function_exists('get_least_viewed_tag')) {
508 function get_least_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
509 global $wpdb;
510 $views_options = get_option('views_options');
511 $where = '';
512 $temp = '';
513 $output = '';
514 if(is_array($tag_id)) {
515 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
516 } else {
517 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
518 }
519 if(!empty($mode) && $mode != 'both') {
520 if(is_array($mode)) {
521 $mode = implode("','",$mode);
522 $where = "post_type IN ('".$mode."')";
523 } else {
524 $where = "post_type = '$mode'";
525 }
526 } else {
527 $where = '1=1';
528 }
529 $most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE post_date < '".current_time('mysql')."' AND $wpdb->term_taxonomy.taxonomy = 'post_tag' AND $tag_sql AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views ASC LIMIT $limit");
530 if($most_viewed) {
531 foreach ($most_viewed as $post) {
532 $post_views = intval($post->views);
533 $post_title = get_the_title($post);
534 if($chars > 0) {
535 $post_title = snippet_text($post_title, $chars);
536 }
537 $thumbnail = get_the_post_thumbnail($post->ID,'thumbnail',true);
538 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
539 $temp = stripslashes($views_options['most_viewed_template']);
540 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
541 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
542 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
543 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
544 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
545 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
546 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
547 $temp = str_replace("%POST_THUMBNAIL%", $thumbnail, $temp);
548 $output .= $temp;
549 }
550 } else {
551 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
552 }
553 if($display) {
554 echo $output;
555 } else {
556 return $output;
557 }
558 }
559 }
560
561
562 ### Function: Display Total Views
563 if(!function_exists('get_totalviews')) {
564 function get_totalviews($display = true) {
565 global $wpdb;
566 $total_views = intval($wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'"));
567 if($display) {
568 echo number_format_i18n($total_views);
569 } else {
570 return $total_views;
571 }
572 }
573 }
574
575
576 ### Function: Snippet Text
577 if(!function_exists('snippet_text')) {
578 function snippet_text($text, $length = 0) {
579 if (defined('MB_OVERLOAD_STRING')) {
580 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
581 if (mb_strlen($text) > $length) {
582 return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
583 } else {
584 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
585 }
586 } else {
587 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
588 if (strlen($text) > $length) {
589 return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
590 } else {
591 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
592 }
593 }
594 }
595 }
596
597
598 ### Function: Process Post Excerpt, For Some Reasons, The Default get_post_excerpt() Does Not Work As Expected
599 function views_post_excerpt($post_excerpt, $post_content, $post_password, $chars = 200) {
600 if(!empty($post_password)) {
601 if(!isset($_COOKIE['wp-postpass_'.COOKIEHASH]) || $_COOKIE['wp-postpass_'.COOKIEHASH] != $post_password) {
602 return __('There is no excerpt because this is a protected post.', 'wp-postviews');
603 }
604 }
605 if(empty($post_excerpt)) {
606 return snippet_text(strip_tags($post_content), $chars);
607 } else {
608 return $post_excerpt;
609 }
610 }
611
612
613 ### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
614 function views_fields($content) {
615 global $wpdb;
616 $content .= ", ($wpdb->postmeta.meta_value+0) AS views";
617 return $content;
618 }
619 function views_join($content) {
620 global $wpdb;
621 $content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
622 return $content;
623 }
624 function views_where($content) {
625 global $wpdb;
626 $content .= " AND $wpdb->postmeta.meta_key = 'views'";
627 return $content;
628 }
629 function views_orderby($content) {
630 $orderby = trim(addslashes(get_query_var('v_orderby')));
631 if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
632 $orderby = 'desc';
633 }
634 $content = " views $orderby";
635 return $content;
636 }
637
638
639 ### Function: Add Views Custom Fields
640 add_action('publish_post', 'add_views_fields');
641 add_action('publish_page', 'add_views_fields');
642 function add_views_fields($post_ID) {
643 global $wpdb;
644 if(!wp_is_post_revision($post_ID)) {
645 add_post_meta($post_ID, 'views', 0, true);
646 }
647 }
648
649
650 ### Function: Views Public Variables
651 add_filter('query_vars', 'views_variables');
652 function views_variables($public_query_vars) {
653 $public_query_vars[] = 'v_sortby';
654 $public_query_vars[] = 'v_orderby';
655 return $public_query_vars;
656 }
657
658
659 ### Function: Sort Views Posts
660 add_action('pre_get_posts', 'views_sorting');
661 function views_sorting($local_wp_query) {
662 if($local_wp_query->get('v_sortby') == 'views') {
663 add_filter('posts_fields', 'views_fields');
664 add_filter('posts_join', 'views_join');
665 add_filter('posts_where', 'views_where');
666 add_filter('posts_orderby', 'views_orderby');
667 } else {
668 remove_filter('posts_fields', 'views_fields');
669 remove_filter('posts_join', 'views_join');
670 remove_filter('posts_where', 'views_where');
671 remove_filter('posts_orderby', 'views_orderby');
672 }
673 }
674
675
676 ### Function: Plug Into WP-Stats
677 add_action( 'plugins_loaded', 'postviews_wp_stats' );
678 function postviews_wp_stats() {
679 add_filter( 'wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats' );
680 add_filter( 'wp_stats_page_admin_most', 'postviews_page_admin_most_stats' );
681 add_filter( 'wp_stats_page_plugins', 'postviews_page_general_stats' );
682 add_filter( 'wp_stats_page_most', 'postviews_page_most_stats' );
683 }
684
685
686 ### Function: Add WP-PostViews General Stats To WP-Stats Page Options
687 function postviews_page_admin_general_stats($content) {
688 $stats_display = get_option('stats_display');
689 if($stats_display['views'] == 1) {
690 $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";
691 } else {
692 $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";
693 }
694 return $content;
695 }
696
697
698 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page Options
699 function postviews_page_admin_most_stats($content) {
700 $stats_display = get_option('stats_display');
701 $stats_mostlimit = intval(get_option('stats_mostlimit'));
702 if($stats_display['viewed_most_post'] == 1) {
703 $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";
704 } else {
705 $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";
706 }
707 if($stats_display['viewed_most_page'] == 1) {
708 $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";
709 } else {
710 $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";
711 }
712 return $content;
713 }
714
715
716 ### Function: Add WP-PostViews General Stats To WP-Stats Page
717 function postviews_page_general_stats($content) {
718 $stats_display = get_option('stats_display');
719 if($stats_display['views'] == 1) {
720 $content .= '<p><strong>'.__('WP-PostViews', 'wp-postviews').'</strong></p>'."\n";
721 $content .= '<ul>'."\n";
722 $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";
723 $content .= '</ul>'."\n";
724 }
725 return $content;
726 }
727
728
729 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page
730 function postviews_page_most_stats($content) {
731 $stats_display = get_option('stats_display');
732 $stats_mostlimit = intval(get_option('stats_mostlimit'));
733 if($stats_display['viewed_most_post'] == 1) {
734 $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";
735 $content .= '<ul>'."\n";
736 $content .= get_most_viewed('post', $stats_mostlimit, 0, false);
737 $content .= '</ul>'."\n";
738 }
739 if($stats_display['viewed_most_page'] == 1) {
740 $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";
741 $content .= '<ul>'."\n";
742 $content .= get_most_viewed('page', $stats_mostlimit, 0, false);
743 $content .= '</ul>'."\n";
744 }
745 return $content;
746 }
747
748
749 ### Function: Increment Post Views
750 add_action( 'wp_ajax_postviews', 'increment_views' );
751 add_action( 'wp_ajax_nopriv_postviews', 'increment_views' );
752 function increment_views() {
753 if( empty( $_GET['postviews_id'] ) )
754 return;
755
756 if( !defined( 'WP_CACHE' ) || !WP_CACHE )
757 return;
758
759 $views_options = get_option( 'views_options' );
760
761 if( isset( $views_options['use_ajax'] ) && intval( $views_options['use_ajax'] ) === 0 )
762 return;
763
764 $post_id = intval( $_GET['postviews_id'] );
765 if( $post_id > 0 ) {
766 $post_views = get_post_custom( $post_id );
767 $post_views = intval( $post_views['views'][0] );
768 update_post_meta( $post_id, 'views', ( $post_views + 1 ) );
769 do_action( 'postviews_increment_views_ajax', ( $post_views + 1 ) );
770 echo ( $post_views + 1 );
771 exit();
772 }
773 }
774
775 ### Function Show Post Views Column in WP-Admin
776 add_action('manage_posts_custom_column', 'add_postviews_column_content');
777 add_filter('manage_posts_columns', 'add_postviews_column');
778 add_action('manage_pages_custom_column', 'add_postviews_column_content');
779 add_filter('manage_pages_columns', 'add_postviews_column');
780 function add_postviews_column($defaults) {
781 $defaults['views'] = __( 'Views', 'wp-postviews' );
782 return $defaults;
783 }
784
785
786 ### Functions Fill In The Views Count
787 function add_postviews_column_content($column_name) {
788 if($column_name == 'views') {
789 if(function_exists('the_views')) { the_views(true, '', '', true); }
790 }
791 }
792
793
794 ### Function Sort Columns
795 add_filter('manage_edit-post_sortable_columns', 'sort_postviews_column');
796 add_filter('manage_edit-page_sortable_columns', 'sort_postviews_column');
797 function sort_postviews_column($defaults)
798 {
799 $defaults['views'] = 'views';
800 return $defaults;
801 }
802 add_action('pre_get_posts', 'sort_postviews');
803 function sort_postviews($query) {
804 if(!is_admin())
805 return;
806 $orderby = $query->get('orderby');
807 if('views' == $orderby) {
808 $query->set('meta_key', 'views');
809 $query->set('orderby', 'meta_value_num');
810 }
811 }
812
813 ### Function: Round Numbers To K (Thousand), M (Million) or B (Billion)
814 function postviews_round_number( $number, $min_value = 1000, $decimal = 1 ) {
815 if( $number < $min_value ) {
816 return number_format_i18n( $number );
817 }
818 $alphabets = array( 1000000000 => 'B', 1000000 => 'M', 1000 => 'K' );
819 foreach( $alphabets as $key => $value )
820 if( $number >= $key ) {
821 return round( $number / $key, $decimal ) . '' . $value;
822 }
823 }
824
825
826 ### Class: WP-PostViews Widget
827 class WP_Widget_PostViews extends WP_Widget {
828 // Constructor
829 function __construct() {
830 $widget_ops = array('description' => __('WP-PostViews views statistics', 'wp-postviews'));
831 parent::__construct('views', __('Views', 'wp-postviews'), $widget_ops);
832 }
833
834 // Display Widget
835 function widget($args, $instance) {
836 $title = apply_filters('widget_title', esc_attr($instance['title']));
837 $type = esc_attr($instance['type']);
838 $mode = esc_attr($instance['mode']);
839 $limit = intval($instance['limit']);
840 $chars = intval($instance['chars']);
841 $cat_ids = explode(',', esc_attr($instance['cat_ids']));
842 echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title'];
843 echo '<ul>'."\n";
844 switch($type) {
845 case 'least_viewed':
846 get_least_viewed($mode, $limit, $chars);
847 break;
848 case 'most_viewed':
849 get_most_viewed($mode, $limit, $chars);
850 break;
851 case 'most_viewed_category':
852 get_most_viewed_category($cat_ids, $mode, $limit, $chars);
853 break;
854 case 'least_viewed_category':
855 get_least_viewed_category($cat_ids, $mode, $limit, $chars);
856 break;
857 }
858 echo '</ul>'."\n";
859 echo $args['after_widget'];
860 }
861
862 // When Widget Control Form Is Posted
863 function update($new_instance, $old_instance) {
864 if (!isset($new_instance['submit'])) {
865 return false;
866 }
867 $instance = $old_instance;
868 $instance['title'] = strip_tags($new_instance['title']);
869 $instance['type'] = strip_tags($new_instance['type']);
870 $instance['mode'] = strip_tags($new_instance['mode']);
871 $instance['limit'] = intval($new_instance['limit']);
872 $instance['chars'] = intval($new_instance['chars']);
873 $instance['cat_ids'] = strip_tags($new_instance['cat_ids']);
874 return $instance;
875 }
876
877 // DIsplay Widget Control Form
878 function form($instance) {
879 $instance = wp_parse_args((array) $instance, array('title' => __('Views', 'wp-postviews'), 'type' => 'most_viewed', 'mode' => '', 'limit' => 10, 'chars' => 200, 'cat_ids' => '0'));
880 $title = esc_attr($instance['title']);
881 $type = esc_attr($instance['type']);
882 $mode = trim(esc_attr($instance['mode']));
883 $limit = intval($instance['limit']);
884 $chars = intval($instance['chars']);
885 $cat_ids = esc_attr($instance['cat_ids']);
886 $post_types = get_post_types(array(
887 'public' => true
888 ));
889 ?>
890 <p>
891 <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>
892 </p>
893 <p>
894 <label for="<?php echo $this->get_field_id('type'); ?>"><?php _e('Statistics Type:', 'wp-postviews'); ?>
895 <select name="<?php echo $this->get_field_name('type'); ?>" id="<?php echo $this->get_field_id('type'); ?>" class="widefat">
896 <option value="least_viewed"<?php selected('least_viewed', $type); ?>><?php _e('Least Viewed', 'wp-postviews'); ?></option>
897 <option value="least_viewed_category"<?php selected('least_viewed_category', $type); ?>><?php _e('Least Viewed By Category', 'wp-postviews'); ?></option>
898 <optgroup>&nbsp;</optgroup>
899 <option value="most_viewed"<?php selected('most_viewed', $type); ?>><?php _e('Most Viewed', 'wp-postviews'); ?></option>
900 <option value="most_viewed_category"<?php selected('most_viewed_category', $type); ?>><?php _e('Most Viewed By Category', 'wp-postviews'); ?></option>
901 </select>
902 </label>
903 </p>
904 <p>
905 <label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Include Views From:', 'wp-postviews'); ?>
906 <select name="<?php echo $this->get_field_name('mode'); ?>" id="<?php echo $this->get_field_id('mode'); ?>" class="widefat">
907 <option value=""<?php selected('', $mode); ?>><?php _e('All', 'wp-postviews'); ?></option>
908 <?php if($post_types > 0): ?>
909 <?php foreach($post_types as $post_type): ?>
910 <option value="<?php echo $post_type; ?>"<?php selected($post_type, $mode); ?>><?php printf(__('%s Only', 'wp-postviews'), ucfirst($post_type)); ?></option>
911 <?php endforeach; ?>
912 <?php endif; ?>
913 </select>
914 </label>
915 </p>
916 <p>
917 <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>
918 </p>
919 <p>
920 <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 />
921 <small><?php _e('<strong>0</strong> to disable.', 'wp-postviews'); ?></small>
922 </p>
923 <p>
924 <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 />
925 <small><?php _e('Seperate mutiple categories with commas.', 'wp-postviews'); ?></small>
926 </p>
927 <p style="color: red;">
928 <small><?php _e('* If you are not using any category statistics, you can ignore it.', 'wp-postviews'); ?></small>
929 <p>
930 <input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
931 <?php
932 }
933 }
934
935
936 ### Function: Init WP-PostViews Widget
937 add_action( 'widgets_init', 'widget_views_init' );
938 function widget_views_init() {
939 register_widget( 'WP_Widget_PostViews' );
940 }
941
942
943 ### Function: Post Views Options
944 register_activation_hook( __FILE__, 'views_activation' );
945 function views_activation( $network_wide ) {
946 // Add Options
947 $option_name = 'views_options';
948 $option = array(
949 'count' => 1
950 , 'exclude_bots' => 0
951 , 'display_home' => 0
952 , 'display_single' => 0
953 , 'display_page' => 0
954 , 'display_archive' => 0
955 , 'display_search' => 0
956 , 'display_other' => 0
957 , 'use_ajax' => 1
958 , 'template' => __('%VIEW_COUNT% views', 'wp-postviews')
959 , 'most_viewed_template' => '<li><a href="%POST_URL%" title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% '.__('views', 'wp-postviews').'</li>'
960 );
961
962 if ( is_multisite() && $network_wide )
963 {
964 $ms_sites = wp_get_sites();
965
966 if( 0 < sizeof( $ms_sites ) )
967 {
968 foreach ( $ms_sites as $ms_site )
969 {
970 switch_to_blog( $ms_site['blog_id'] );
971 add_option( $option_name, $option );
972 }
973 }
974
975 restore_current_blog();
976 }
977 else
978 {
979 add_option( $option_name, $option );
980 }
981 }
982
983 ### Function: Parse View Options
984 function views_options_parse($key) {
985 return !empty($_POST[$key]) ? $_POST[$key] : null;
986 }
987