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

959 lines 36.9 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.68
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(post_custom('views'));
204 $views_options = get_option('views_options');
205 if ($always || should_views_be_displayed($views_options)) {
206 $output = $prefix.str_replace('%VIEW_COUNT%', number_format_i18n($post_views), $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
219 ### Function: Display Least Viewed Page/Post
220 if(!function_exists('get_least_viewed')) {
221 function get_least_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
222 global $wpdb;
223 $views_options = get_option('views_options');
224 $where = '';
225 $temp = '';
226 $output = '';
227 if(!empty($mode) && $mode != 'both') {
228 if(is_array($mode)) {
229 $mode = implode("','",$mode);
230 $where = "post_type IN ('".$mode."')";
231 } else {
232 $where = "post_type = '$mode'";
233 }
234 } else {
235 $where = '1=1';
236 }
237 $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");
238 if($most_viewed) {
239 foreach ($most_viewed as $post) {
240 $post_views = intval($post->views);
241 $post_title = get_the_title($post);
242 if($chars > 0) {
243 $post_title = snippet_text($post_title, $chars);
244 }
245 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
246 $temp = stripslashes($views_options['most_viewed_template']);
247 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
248 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
249 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
250 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
251 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
252 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
253 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
254 $output .= $temp;
255 }
256 } else {
257 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
258 }
259 if($display) {
260 echo $output;
261 } else {
262 return $output;
263 }
264 }
265 }
266
267
268 ### Function: Display Most Viewed Page/Post
269 if(!function_exists('get_most_viewed')) {
270 function get_most_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
271 global $wpdb;
272 $views_options = get_option('views_options');
273 $where = '';
274 $temp = '';
275 $output = '';
276 if(!empty($mode) && $mode != 'both') {
277 if(is_array($mode)) {
278 $mode = implode("','",$mode);
279 $where = "post_type IN ('".$mode."')";
280 } else {
281 $where = "post_type = '$mode'";
282 }
283 } else {
284 $where = '1=1';
285 }
286 $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");
287 if($most_viewed) {
288 foreach ($most_viewed as $post) {
289 $post_views = intval($post->views);
290 $post_title = get_the_title($post);
291 if($chars > 0) {
292 $post_title = snippet_text($post_title, $chars);
293 }
294 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
295 $temp = stripslashes($views_options['most_viewed_template']);
296 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
297 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
298 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
299 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
300 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
301 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
302 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
303 $output .= $temp;
304 }
305 } else {
306 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
307 }
308 if($display) {
309 echo $output;
310 } else {
311 return $output;
312 }
313 }
314 }
315
316
317 ### Function: Display Leased Viewed Page/Post By Category ID
318 if(!function_exists('get_least_viewed_category')) {
319 function get_least_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
320 global $wpdb;
321 $views_options = get_option('views_options');
322 $where = '';
323 $temp = '';
324 $output = '';
325 if(is_array($category_id)) {
326 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
327 } else {
328 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
329 }
330 if(!empty($mode) && $mode != 'both') {
331 if(is_array($mode)) {
332 $mode = implode("','",$mode);
333 $where = "post_type IN ('".$mode."')";
334 } else {
335 $where = "post_type = '$mode'";
336 }
337 } else {
338 $where = '1=1';
339 }
340 $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");
341 if($most_viewed) {
342 foreach ($most_viewed as $post) {
343 $post_views = intval($post->views);
344 $post_title = get_the_title($post);
345 if($chars > 0) {
346 $post_title = snippet_text($post_title, $chars);
347 }
348 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
349 $temp = stripslashes($views_options['most_viewed_template']);
350 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
351 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
352 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
353 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
354 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
355 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
356 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
357 $output .= $temp;
358 }
359 } else {
360 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
361 }
362 if($display) {
363 echo $output;
364 } else {
365 return $output;
366 }
367 }
368 }
369
370
371 ### Function: Display Most Viewed Page/Post By Category ID
372 if(!function_exists('get_most_viewed_category')) {
373 function get_most_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
374 global $wpdb;
375 $views_options = get_option('views_options');
376 $where = '';
377 $temp = '';
378 $output = '';
379 if(is_array($category_id)) {
380 $category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
381 } else {
382 $category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
383 }
384 if(!empty($mode) && $mode != 'both') {
385 if(is_array($mode)) {
386 $mode = implode("','",$mode);
387 $where = "post_type IN ('".$mode."')";
388 } else {
389 $where = "post_type = '$mode'";
390 }
391 } else {
392 $where = '1=1';
393 }
394 $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");
395 if($most_viewed) {
396 foreach ($most_viewed as $post) {
397 $post_views = intval($post->views);
398 $post_title = get_the_title($post);
399 if($chars > 0) {
400 $post_title = snippet_text($post_title, $chars);
401 }
402 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
403 $temp = stripslashes($views_options['most_viewed_template']);
404 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
405 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
406 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
407 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
408 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
409 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
410 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
411 $output .= $temp;
412 }
413 } else {
414 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
415 }
416 if($display) {
417 echo $output;
418 } else {
419 return $output;
420 }
421 }
422 }
423
424
425 ### Function: Display Most Viewed Page/Post By Tag ID
426 if(!function_exists('get_most_viewed_tag')) {
427 function get_most_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
428 global $wpdb;
429 $views_options = get_option('views_options');
430 $where = '';
431 $temp = '';
432 $output = '';
433 if(is_array($tag_id)) {
434 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
435 } else {
436 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
437 }
438 if(!empty($mode) && $mode != 'both') {
439 if(is_array($mode)) {
440 $mode = implode("','",$mode);
441 $where = "post_type IN ('".$mode."')";
442 } else {
443 $where = "post_type = '$mode'";
444 }
445 } else {
446 $where = '1=1';
447 }
448 $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");
449 if($most_viewed) {
450 foreach ($most_viewed as $post) {
451 $post_views = intval($post->views);
452 $post_title = get_the_title($post);
453 if($chars > 0) {
454 $post_title = snippet_text($post_title, $chars);
455 }
456 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
457 $temp = stripslashes($views_options['most_viewed_template']);
458 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
459 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
460 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
461 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
462 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
463 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
464 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
465 $output .= $temp;
466 }
467 } else {
468 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
469 }
470 if($display) {
471 echo $output;
472 } else {
473 return $output;
474 }
475 }
476 }
477
478
479 ### Function: Display Least Viewed Page/Post By Tag ID
480 if(!function_exists('get_least_viewed_tag')) {
481 function get_least_viewed_tag($tag_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
482 global $wpdb;
483 $views_options = get_option('views_options');
484 $where = '';
485 $temp = '';
486 $output = '';
487 if(is_array($tag_id)) {
488 $tag_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $tag_id).')';
489 } else {
490 $tag_sql = "$wpdb->term_taxonomy.term_id = $tag_id";
491 }
492 if(!empty($mode) && $mode != 'both') {
493 if(is_array($mode)) {
494 $mode = implode("','",$mode);
495 $where = "post_type IN ('".$mode."')";
496 } else {
497 $where = "post_type = '$mode'";
498 }
499 } else {
500 $where = '1=1';
501 }
502 $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");
503 if($most_viewed) {
504 foreach ($most_viewed as $post) {
505 $post_views = intval($post->views);
506 $post_title = get_the_title($post);
507 if($chars > 0) {
508 $post_title = snippet_text($post_title, $chars);
509 }
510 $post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
511 $temp = stripslashes($views_options['most_viewed_template']);
512 $temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
513 $temp = str_replace("%POST_TITLE%", $post_title, $temp);
514 $temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
515 $temp = str_replace("%POST_CONTENT%", $post->post_content, $temp);
516 $temp = str_replace("%POST_URL%", get_permalink($post), $temp);
517 $temp = str_replace("%POST_DATE%", get_the_time(get_option('date_format'), $post), $temp);
518 $temp = str_replace("%POST_TIME%", get_the_time(get_option('time_format'), $post), $temp);
519 $output .= $temp;
520 }
521 } else {
522 $output = '<li>'.__('N/A', 'wp-postviews').'</li>'."\n";
523 }
524 if($display) {
525 echo $output;
526 } else {
527 return $output;
528 }
529 }
530 }
531
532
533 ### Function: Display Total Views
534 if(!function_exists('get_totalviews')) {
535 function get_totalviews($display = true) {
536 global $wpdb;
537 $total_views = intval($wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'"));
538 if($display) {
539 echo number_format_i18n($total_views);
540 } else {
541 return $total_views;
542 }
543 }
544 }
545
546
547 ### Function: Snippet Text
548 if(!function_exists('snippet_text')) {
549 function snippet_text($text, $length = 0) {
550 if (defined('MB_OVERLOAD_STRING')) {
551 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
552 if (mb_strlen($text) > $length) {
553 return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
554 } else {
555 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
556 }
557 } else {
558 $text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
559 if (strlen($text) > $length) {
560 return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
561 } else {
562 return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
563 }
564 }
565 }
566 }
567
568
569 ### Function: Process Post Excerpt, For Some Reasons, The Default get_post_excerpt() Does Not Work As Expected
570 function views_post_excerpt($post_excerpt, $post_content, $post_password, $chars = 200) {
571 if(!empty($post_password)) {
572 if(!isset($_COOKIE['wp-postpass_'.COOKIEHASH]) || $_COOKIE['wp-postpass_'.COOKIEHASH] != $post_password) {
573 return __('There is no excerpt because this is a protected post.', 'wp-postviews');
574 }
575 }
576 if(empty($post_excerpt)) {
577 return snippet_text(strip_tags($post_content), $chars);
578 } else {
579 return $post_excerpt;
580 }
581 }
582
583
584 ### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
585 function views_fields($content) {
586 global $wpdb;
587 $content .= ", ($wpdb->postmeta.meta_value+0) AS views";
588 return $content;
589 }
590 function views_join($content) {
591 global $wpdb;
592 $content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
593 return $content;
594 }
595 function views_where($content) {
596 global $wpdb;
597 $content .= " AND $wpdb->postmeta.meta_key = 'views'";
598 return $content;
599 }
600 function views_orderby($content) {
601 $orderby = trim(addslashes(get_query_var('v_orderby')));
602 if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
603 $orderby = 'desc';
604 }
605 $content = " views $orderby";
606 return $content;
607 }
608
609
610 ### Function: Add Views Custom Fields
611 add_action('publish_post', 'add_views_fields');
612 add_action('publish_page', 'add_views_fields');
613 function add_views_fields($post_ID) {
614 global $wpdb;
615 if(!wp_is_post_revision($post_ID)) {
616 add_post_meta($post_ID, 'views', 0, true);
617 }
618 }
619
620
621 ### Function: Delete Views Custom Fields
622 add_action('delete_post', 'delete_views_fields');
623 function delete_views_fields($post_ID) {
624 global $wpdb;
625 if(!wp_is_post_revision($post_ID)) {
626 delete_post_meta($post_ID, 'views');
627 }
628 }
629
630
631 ### Function: Views Public Variables
632 add_filter('query_vars', 'views_variables');
633 function views_variables($public_query_vars) {
634 $public_query_vars[] = 'v_sortby';
635 $public_query_vars[] = 'v_orderby';
636 return $public_query_vars;
637 }
638
639
640 ### Function: Sort Views Posts
641 add_action('pre_get_posts', 'views_sorting');
642 function views_sorting($local_wp_query) {
643 if($local_wp_query->get('v_sortby') == 'views') {
644 add_filter('posts_fields', 'views_fields');
645 add_filter('posts_join', 'views_join');
646 add_filter('posts_where', 'views_where');
647 add_filter('posts_orderby', 'views_orderby');
648 } else {
649 remove_filter('posts_fields', 'views_fields');
650 remove_filter('posts_join', 'views_join');
651 remove_filter('posts_where', 'views_where');
652 remove_filter('posts_orderby', 'views_orderby');
653 }
654 }
655
656
657 ### Function: Plug Into WP-Stats
658 add_action('wp','postviews_wp_stats');
659 function postviews_wp_stats() {
660 if(function_exists('stats_page')) {
661 if(strpos(get_option('stats_url'), $_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'], 'stats-options.php') || strpos($_SERVER['REQUEST_URI'], 'wp-stats/wp-stats.php')) {
662 add_filter('wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats');
663 add_filter('wp_stats_page_admin_most', 'postviews_page_admin_most_stats');
664 add_filter('wp_stats_page_plugins', 'postviews_page_general_stats');
665 add_filter('wp_stats_page_most', 'postviews_page_most_stats');
666 }
667 }
668 }
669
670
671 ### Function: Add WP-PostViews General Stats To WP-Stats Page Options
672 function postviews_page_admin_general_stats($content) {
673 $stats_display = get_option('stats_display');
674 if($stats_display['views'] == 1) {
675 $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";
676 } else {
677 $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";
678 }
679 return $content;
680 }
681
682
683 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page Options
684 function postviews_page_admin_most_stats($content) {
685 $stats_display = get_option('stats_display');
686 $stats_mostlimit = intval(get_option('stats_mostlimit'));
687 if($stats_display['viewed_most_post'] == 1) {
688 $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";
689 } else {
690 $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";
691 }
692 if($stats_display['viewed_most_page'] == 1) {
693 $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";
694 } else {
695 $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";
696 }
697 return $content;
698 }
699
700
701 ### Function: Add WP-PostViews General Stats To WP-Stats Page
702 function postviews_page_general_stats($content) {
703 $stats_display = get_option('stats_display');
704 if($stats_display['views'] == 1) {
705 $content .= '<p><strong>'.__('WP-PostViews', 'wp-postviews').'</strong></p>'."\n";
706 $content .= '<ul>'."\n";
707 $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";
708 $content .= '</ul>'."\n";
709 }
710 return $content;
711 }
712
713
714 ### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page
715 function postviews_page_most_stats($content) {
716 $stats_display = get_option('stats_display');
717 $stats_mostlimit = intval(get_option('stats_mostlimit'));
718 if($stats_display['viewed_most_post'] == 1) {
719 $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";
720 $content .= '<ul>'."\n";
721 $content .= get_most_viewed('post', $stats_mostlimit, 0, false);
722 $content .= '</ul>'."\n";
723 }
724 if($stats_display['viewed_most_page'] == 1) {
725 $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";
726 $content .= '<ul>'."\n";
727 $content .= get_most_viewed('page', $stats_mostlimit, 0, false);
728 $content .= '</ul>'."\n";
729 }
730 return $content;
731 }
732
733
734 ### Function: Increment Post Views
735 add_action( 'wp_ajax_postviews', 'increment_views' );
736 add_action( 'wp_ajax_nopriv_postviews', 'increment_views' );
737 function increment_views() {
738 if( empty( $_GET['postviews_id'] ) )
739 return;
740
741 if( !defined( 'WP_CACHE' ) || !WP_CACHE )
742 return;
743
744 $views_options = get_option( 'views_options' );
745
746 if( isset( $views_options['use_ajax'] ) && intval( $views_options['use_ajax'] ) === 0 )
747 return;
748
749 $post_id = intval( $_GET['postviews_id'] );
750 if( $post_id > 0 ) {
751 $post_views = get_post_custom( $post_id );
752 $post_views = intval( $post_views['views'][0] );
753 update_post_meta( $post_id, 'views', ( $post_views + 1 ) );
754 do_action( 'postviews_increment_views_ajax', ( $post_views + 1 ) );
755 echo ( $post_views + 1 );
756 exit();
757 }
758 }
759
760 ### Function Show Post Views Column in WP-Admin
761 add_action('manage_posts_custom_column', 'add_postviews_column_content');
762 add_filter('manage_posts_columns', 'add_postviews_column');
763 add_action('manage_pages_custom_column', 'add_postviews_column_content');
764 add_filter('manage_pages_columns', 'add_postviews_column');
765 function add_postviews_column($defaults) {
766 $defaults['views'] = __( 'Views', 'wp-postviews' );
767 return $defaults;
768 }
769
770
771 ### Functions Fill In The Views Count
772 function add_postviews_column_content($column_name) {
773 if($column_name == 'views') {
774 if(function_exists('the_views')) { the_views(true, '', '', true); }
775 }
776 }
777
778
779 ### Function Sort Columns
780 add_filter('manage_edit-post_sortable_columns', 'sort_postviews_column');
781 add_filter('manage_edit-page_sortable_columns', 'sort_postviews_column');
782 function sort_postviews_column($defaults)
783 {
784 $defaults['views'] = 'views';
785 return $defaults;
786 }
787 add_action('pre_get_posts', 'sort_postviews');
788 function sort_postviews($query) {
789 if(!is_admin())
790 return;
791 $orderby = $query->get('orderby');
792 if('views' == $orderby) {
793 $query->set('meta_key', 'views');
794 $query->set('orderby', 'meta_value_num');
795 }
796 }
797
798
799 ### Class: WP-PostViews Widget
800 class WP_Widget_PostViews extends WP_Widget {
801 // Constructor
802 function WP_Widget_PostViews() {
803 $widget_ops = array('description' => __('WP-PostViews views statistics', 'wp-postviews'));
804 $this->WP_Widget('views', __('Views', 'wp-postviews'), $widget_ops);
805 }
806
807 // Display Widget
808 function widget($args, $instance) {
809 $title = apply_filters('widget_title', esc_attr($instance['title']));
810 $type = esc_attr($instance['type']);
811 $mode = esc_attr($instance['mode']);
812 $limit = intval($instance['limit']);
813 $chars = intval($instance['chars']);
814 $cat_ids = explode(',', esc_attr($instance['cat_ids']));
815 echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title'];
816 echo '<ul>'."\n";
817 switch($type) {
818 case 'least_viewed':
819 get_least_viewed($mode, $limit, $chars);
820 break;
821 case 'most_viewed':
822 get_most_viewed($mode, $limit, $chars);
823 break;
824 case 'most_viewed_category':
825 get_most_viewed_category($cat_ids, $mode, $limit, $chars);
826 break;
827 case 'least_viewed_category':
828 get_least_viewed_category($cat_ids, $mode, $limit, $chars);
829 break;
830 }
831 echo '</ul>'."\n";
832 echo $args['after_widget'];
833 }
834
835 // When Widget Control Form Is Posted
836 function update($new_instance, $old_instance) {
837 if (!isset($new_instance['submit'])) {
838 return false;
839 }
840 $instance = $old_instance;
841 $instance['title'] = strip_tags($new_instance['title']);
842 $instance['type'] = strip_tags($new_instance['type']);
843 $instance['mode'] = strip_tags($new_instance['mode']);
844 $instance['limit'] = intval($new_instance['limit']);
845 $instance['chars'] = intval($new_instance['chars']);
846 $instance['cat_ids'] = strip_tags($new_instance['cat_ids']);
847 return $instance;
848 }
849
850 // DIsplay Widget Control Form
851 function form($instance) {
852 $instance = wp_parse_args((array) $instance, array('title' => __('Views', 'wp-postviews'), 'type' => 'most_viewed', 'mode' => '', 'limit' => 10, 'chars' => 200, 'cat_ids' => '0'));
853 $title = esc_attr($instance['title']);
854 $type = esc_attr($instance['type']);
855 $mode = trim(esc_attr($instance['mode']));
856 $limit = intval($instance['limit']);
857 $chars = intval($instance['chars']);
858 $cat_ids = esc_attr($instance['cat_ids']);
859 $post_types = get_post_types(array(
860 'public' => true
861 ));
862 ?>
863 <p>
864 <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>
865 </p>
866 <p>
867 <label for="<?php echo $this->get_field_id('type'); ?>"><?php _e('Statistics Type:', 'wp-postviews'); ?>
868 <select name="<?php echo $this->get_field_name('type'); ?>" id="<?php echo $this->get_field_id('type'); ?>" class="widefat">
869 <option value="least_viewed"<?php selected('least_viewed', $type); ?>><?php _e('Least Viewed', 'wp-postviews'); ?></option>
870 <option value="least_viewed_category"<?php selected('least_viewed_category', $type); ?>><?php _e('Least Viewed By Category', 'wp-postviews'); ?></option>
871 <optgroup>&nbsp;</optgroup>
872 <option value="most_viewed"<?php selected('most_viewed', $type); ?>><?php _e('Most Viewed', 'wp-postviews'); ?></option>
873 <option value="most_viewed_category"<?php selected('most_viewed_category', $type); ?>><?php _e('Most Viewed By Category', 'wp-postviews'); ?></option>
874 </select>
875 </label>
876 </p>
877 <p>
878 <label for="<?php echo $this->get_field_id('mode'); ?>"><?php _e('Include Views From:', 'wp-postviews'); ?>
879 <select name="<?php echo $this->get_field_name('mode'); ?>" id="<?php echo $this->get_field_id('mode'); ?>" class="widefat">
880 <option value=""<?php selected('', $mode); ?>><?php _e('All', 'wp-postviews'); ?></option>
881 <?php if($post_types > 0): ?>
882 <?php foreach($post_types as $post_type): ?>
883 <option value="<?php echo $post_type; ?>"<?php selected($post_type, $mode); ?>><?php printf(__('%s Only', 'wp-postviews'), ucfirst($post_type)); ?></option>
884 <?php endforeach; ?>
885 <?php endif; ?>
886 </select>
887 </label>
888 </p>
889 <p>
890 <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>
891 </p>
892 <p>
893 <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 />
894 <small><?php _e('<strong>0</strong> to disable.', 'wp-postviews'); ?></small>
895 </p>
896 <p>
897 <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 />
898 <small><?php _e('Seperate mutiple categories with commas.', 'wp-postviews'); ?></small>
899 </p>
900 <p style="color: red;">
901 <small><?php _e('* If you are not using any category statistics, you can ignore it.', 'wp-postviews'); ?></small>
902 <p>
903 <input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
904 <?php
905 }
906 }
907
908
909 ### Function: Init WP-PostViews Widget
910 add_action( 'widgets_init', 'widget_views_init' );
911 function widget_views_init() {
912 register_widget( 'WP_Widget_PostViews' );
913 }
914
915
916 ### Function: Post Views Options
917 register_activation_hook( __FILE__, 'views_activation' );
918 function views_activation( $network_wide ) {
919 // Add Options
920 $option_name = 'views_options';
921 $option = array(
922 'count' => 1
923 , 'exclude_bots' => 0
924 , 'display_home' => 0
925 , 'display_single' => 0
926 , 'display_page' => 0
927 , 'display_archive' => 0
928 , 'display_search' => 0
929 , 'display_other' => 0
930 , 'use_ajax' => 1
931 , 'template' => __('%VIEW_COUNT% views', 'wp-postviews')
932 , 'most_viewed_template' => '<li><a href="%POST_URL%" title="%POST_TITLE%">%POST_TITLE%</a> - %VIEW_COUNT% '.__('views', 'wp-postviews').'</li>'
933 );
934
935 if ( is_multisite() && $network_wide )
936 {
937 $ms_sites = wp_get_sites();
938
939 if( 0 < sizeof( $ms_sites ) )
940 {
941 foreach ( $ms_sites as $ms_site )
942 {
943 switch_to_blog( $ms_site['blog_id'] );
944 add_option( $option_name, $option );
945 }
946 }
947
948 restore_current_blog();
949 }
950 else
951 {
952 add_option( $option_name, $option );
953 }
954 }
955
956 ### Function: Parse View Options
957 function views_options_parse($key) {
958 return !empty($_POST[$key]) ? $_POST[$key] : null;
959 }