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

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