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

986 lines 38.1 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.69
7 Author: Lester 'GaMerZ' Chan
8 Author URI: http://lesterchan.net
9 Text Domain: wp-postviews
10 */
11
12
13 /*
14 Copyright 2014 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 ) ) {
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 $temp = stripslashes($views_options['most_viewed_template']);
262 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
263 $temp = str_replace("%VIEW_COUNT_ROUNDED%", postviews_round_number( $post_views ), $temp);
264 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
265 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
266 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
267 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
268 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
269 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
270 $output .= $temp;
271 }
272 } else {
273 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
274 }
275 if($display) {
276 echo $output;
277 } else {
278 return $output;
279 }
280 }
281 }
282
283
284 ### Function: Display Most Viewed Page/Post
285 if(!function_exists('get_most_viewed')) {
286 function get_most_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
287 global $wpdb;
288 $views_options = get_option('views_options');
289 $where = '';
290 $temp = '';
291 $output = '';
292 if(!empty($mode) && $mode != 'both') {
293 if(is_array($mode)) {
294 $mode = implode("','",$mode);
295 $where = "post_type IN ('".$mode."')";
296 } else {
297 $where = "post_type = '$mode'";
298 }
299 } else {
300 $where = '1=1';
301 }
302 $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");
303 if($most_viewed) {
304 foreach ($most_viewed as $post) {
305 $post_views = intval($post->views);
306 $post_title = get_the_title($post);
307 if($chars > 0) {
308 $post_title = snippet_text($post_title, $chars);
309 }
310 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
311 $temp = stripslashes($views_options['most_viewed_template']);
312 $temp = str_replace("%VIEW_COUNT%", number_format_i18n( $post_views ), $temp);
313 $temp = str_replace("%VIEW_COUNT_ROUNDED%", postviews_round_number( $post_views ), $temp);
314 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
315 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
316 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
317 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
318 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
319 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
320 $output .= $temp;
321 }
322 } else {
323 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
324 }
325 if($display) {
326 echo $output;
327 } else {
328 return $output;
329 }
330 }
331 }
332
333
334 ### Function: Display Leased Viewed Page/Post By Category ID
335 if(!function_exists('get_least_viewed_category')) {
336 function get_least_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
337 global $wpdb;
338 $views_options = get_option('views_options');
339 $where = '';
340 $temp = '';
341 $output = '';
342 if(is_array($category_id)) {
343 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
344 } else {
345 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
346 }
347 if(!empty($mode) && $mode != 'both') {
348 if(is_array($mode)) {
349 $mode = implode("','",$mode);
350 $where = "post_type IN ('".$mode."')";
351 } else {
352 $where = "post_type = '$mode'";
353 }
354 } else {
355 $where = '1=1';
356 }
357 $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");
358 if($most_viewed) {
359 foreach ($most_viewed as $post) {
360 $post_views = intval($post->views);
361 $post_title = get_the_title($post);
362 if($chars > 0) {
363 $post_title = snippet_text($post_title, $chars);
364 }
365 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
366 $temp = stripslashes($views_options['most_viewed_template']);
367 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
368 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
369 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
370 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
371 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
372 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
373 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
374 $output .= $temp;
375 }
376 } else {
377 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
378 }
379 if($display) {
380 echo $output;
381 } else {
382 return $output;
383 }
384 }
385 }
386
387
388 ### Function: Display Most Viewed Page/Post By Category ID
389 if(!function_exists('get_most_viewed_category')) {
390 function get_most_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
391 global $wpdb;
392 $views_options = get_option('views_options');
393 $where = '';
394 $temp = '';
395 $output = '';
396 if(is_array($category_id)) {
397 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
398 } else {
399 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
400 }
401 if(!empty($mode) && $mode != 'both') {
402 if(is_array($mode)) {
403 $mode = implode("','",$mode);
404 $where = "post_type IN ('".$mode."')";
405 } else {
406 $where = "post_type = '$mode'";
407 }
408 } else {
409 $where = '1=1';
410 }
411 $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");
412 if($most_viewed) {
413 foreach ($most_viewed as $post) {
414 $post_views = intval($post->views);
415 $post_title = get_the_title($post);
416 if($chars > 0) {
417 $post_title = snippet_text($post_title, $chars);
418 }
419 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
420 $temp = stripslashes($views_options['most_viewed_template']);
421 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
422 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
423 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
424 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
425 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
426 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
427 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
428 $output .= $temp;
429 }
430 } else {
431 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
432 }
433 if($display) {
434 echo $output;
435 } else {
436 return $output;
437 }
438 }
439 }
440
441
442 ### Function: Display Most Viewed Page/Post By Tag ID
443 if(!function_exists('get_most_viewed_tag')) {
444 function get_most_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
445 global $wpdb;
446 $views_options = get_option('views_options');
447 $where = '';
448 $temp = '';
449 $output = '';
450 if(is_array($tag_id)) {
451 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
452 } else {
453 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
454 }
455 if(!empty($mode) && $mode != 'both') {
456 if(is_array($mode)) {
457 $mode = implode("','",$mode);
458 $where = "post_type IN ('".$mode."')";
459 } else {
460 $where = "post_type = '$mode'";
461 }
462 } else {
463 $where = '1=1';
464 }
465 $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");
466 if($most_viewed) {
467 foreach ($most_viewed as $post) {
468 $post_views = intval($post->views);
469 $post_title = get_the_title($post);
470 if($chars > 0) {
471 $post_title = snippet_text($post_title, $chars);
472 }
473 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
474 $temp = stripslashes($views_options['most_viewed_template']);
475 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
476 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
477 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
478 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
479 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
480 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
481 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
482 $output .= $temp;
483 }
484 } else {
485 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
486 }
487 if($display) {
488 echo $output;
489 } else {
490 return $output;
491 }
492 }
493 }
494
495
496 ### Function: Display Least Viewed Page/Post By Tag ID
497 if(!function_exists('get_least_viewed_tag')) {
498 function get_least_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
499 global $wpdb;
500 $views_options = get_option('views_options');
501 $where = '';
502 $temp = '';
503 $output = '';
504 if(is_array($tag_id)) {
505 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
506 } else {
507 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
508 }
509 if(!empty($mode) && $mode != 'both') {
510 if(is_array($mode)) {
511 $mode = implode("','",$mode);
512 $where = "post_type IN ('".$mode."')";
513 } else {
514 $where = "post_type = '$mode'";
515 }
516 } else {
517 $where = '1=1';
518 }
519 $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");
520 if($most_viewed) {
521 foreach ($most_viewed as $post) {
522 $post_views = intval($post->views);
523 $post_title = get_the_title($post);
524 if($chars > 0) {
525 $post_title = snippet_text($post_title, $chars);
526 }
527 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
528 $temp = stripslashes($views_options['most_viewed_template']);
529 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
530 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
531 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
532 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
533 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
534 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
535 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
536 $output .= $temp;
537 }
538 } else {
539 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
540 }
541 if($display) {
542 echo $output;
543 } else {
544 return $output;
545 }
546 }
547 }
548
549
550 ### Function: Display Total Views
551 if(!function_exists('get_totalviews')) {
552 function get_totalviews($display = true) {
553 global $wpdb;
554 $total_views = intval($wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'"));
555 if($display) {
556 echo number_format_i18n($total_views);
557 } else {
558 return $total_views;
559 }
560 }
561 }
562
563
564 ### Function: Snippet Text
565 if(!function_exists('snippet_text')) {
566 function snippet_text($text, $length = 0) {
567 if (defined('MB_OVERLOAD_STRING')) {
568 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
569 if (mb_strlen($text) > $length) {
570 return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
571 } else {
572 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
573 }
574 } else {
575 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
576 if (strlen($text) > $length) {
577 return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
578 } else {
579 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
580 }
581 }
582 }
583 }
584
585
586 ### Function: Process Post Excerpt, For Some Reasons, The Default get_post_excerpt() Does Not Work As Expected
587 function views_post_excerpt($post_excerpt, $post_content, $post_password, $chars = 200) {
588 if(!empty($post_password)) {
589 if(!isset($_COOKIE['wp-postpass_'.COOKIEHASH]) || $_COOKIE['wp-postpass_'.COOKIEHASH] != $post_password) {
590 return __('There is no excerpt because this is a protected post.', 'wp-postviews');
591 }
592 }
593 if(empty($post_excerpt)) {
594 return snippet_text(strip_tags($post_content), $chars);
595 } else {
596 return $post_excerpt;
597 }
598 }
599
600
601 ### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
602 function views_fields($content) {
603 global $wpdb;
604 $content .= ", ($wpdb->postmeta.meta_value+0) AS views";
605 return $content;
606 }
607 function views_join($content) {
608 global $wpdb;
609 $content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
610 return $content;
611 }
612 function views_where($content) {
613 global $wpdb;
614 $content .= " AND $wpdb->postmeta.meta_key = 'views'";
615 return $content;
616 }
617 function views_orderby($content) {
618 $orderby = trim(addslashes(get_query_var('v_orderby')));
619 if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
620 $orderby = 'desc';
621 }
622 $content = " views $orderby";
623 return $content;
624 }
625
626
627 ### Function: Add Views Custom Fields
628 add_action('publish_post', 'add_views_fields');
629 add_action('publish_page', 'add_views_fields');
630 function add_views_fields($post_ID) {
631 global $wpdb;
632 if(!wp_is_post_revision($post_ID)) {
633 add_post_meta($post_ID, 'views', 0, true);
634 }
635 }
636
637
638 ### Function: Delete Views Custom Fields
639 add_action('delete_post', 'delete_views_fields');
640 function delete_views_fields($post_ID) {
641 global $wpdb;
642 if(!wp_is_post_revision($post_ID)) {
643 delete_post_meta($post_ID, 'views');
644 }
645 }
646
647
648 ### Function: Views Public Variables
649 add_filter('query_vars', 'views_variables');
650 function views_variables($public_query_vars) {
651 $public_query_vars[] = 'v_sortby';
652 $public_query_vars[] = 'v_orderby';
653 return $public_query_vars;
654 }
655
656
657 ### Function: Sort Views Posts
658 add_action('pre_get_posts', 'views_sorting');
659 function views_sorting($local_wp_query) {
660 if($local_wp_query->get('v_sortby') == 'views') {
661 add_filter('posts_fields', 'views_fields');
662 add_filter('posts_join', 'views_join');
663 add_filter('posts_where', 'views_where');
664 add_filter('posts_orderby', 'views_orderby');
665 } else {
666 remove_filter('posts_fields', 'views_fields');
667 remove_filter('posts_join', 'views_join');
668 remove_filter('posts_where', 'views_where');
669 remove_filter('posts_orderby', 'views_orderby');
670 }
671 }
672
673
674 ### Function: Plug Into WP-Stats
675 add_action('wp','postviews_wp_stats');
676 function postviews_wp_stats() {
677 if(function_exists('stats_page')) {
678 add_filter('wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats');
679 add_filter('wp_stats_page_admin_most', 'postviews_page_admin_most_stats');
680 add_filter('wp_stats_page_plugins', 'postviews_page_general_stats');
681 add_filter('wp_stats_page_most', 'postviews_page_most_stats');
682 }
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 WP_Widget_PostViews() {
830 $widget_ops = array('description' => __('WP-PostViews views statistics', 'wp-postviews'));
831 $this->WP_Widget('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 }