David Potter to include options for when and where to display view counts.
Version: 1.40
Author: Lester 'GaMerZ' Chan
Author URI: http://lesterchan.net
*/
/*
Copyright 2008 Lester Chan (email : lesterchan@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
### Load WP-Config File If This File Is Called Directly
if (!function_exists('add_action')) {
$wp_root = '../../..';
if (file_exists($wp_root.'/wp-load.php')) {
require_once($wp_root.'/wp-load.php');
} else {
require_once($wp_root.'/wp-config.php');
}
}
### Create Text Domain For Translations
add_action('init', 'postviews_textdomain');
function postviews_textdomain() {
load_plugin_textdomain('wp-postviews', false, 'wp-postviews');
}
### Function: Post Views Option Menu
add_action('admin_menu', 'postviews_menu');
function postviews_menu() {
if (function_exists('add_options_page')) {
add_options_page(__('PostViews', 'wp-postviews'), __('PostViews', 'wp-postviews'), 'manage_options', 'wp-postviews/postviews-options.php') ;
}
}
### Function: Calculate Post Views
add_action('wp_head', 'process_postviews');
function process_postviews() {
global $user_ID, $post;
if(is_single() || is_page()) {
$id = intval($post->ID);
$views_options = get_option('views_options');
$post_views = get_post_custom($id);
$post_views = intval($post_views['views'][0]);
$should_count = false;
switch(intval($views_options['count'])) {
case 0:
$should_count = true;
break;
case 1:
if(empty($_COOKIE[USER_COOKIE]) && intval($user_ID) == 0) {
$should_count = true;
}
break;
case 2:
if(intval($user_ID) > 0) {
$should_count = true;
}
break;
}
if(intval($views_options['exclude_bots']) == 1) {
$bots = array('Google Bot' => 'googlebot', 'Google Bot' => 'google', 'MSN' => 'msnbot', 'Alex' => 'ia_archiver', 'Lycos' => 'lycos', 'Ask Jeeves' => 'jeeves', 'Altavista' => 'scooter', 'AllTheWeb' => 'fast-webcrawler', 'Inktomi' => 'slurp@inktomi', 'Turnitin.com' => 'turnitinbot', 'Technorati' => 'technorati', 'Yahoo' => 'yahoo', 'Findexa' => 'findexa', 'NextLinks' => 'findlinks', 'Gais' => 'gaisbo', 'WiseNut' => 'zyborg', 'WhoisSource' => 'surveybot', 'Bloglines' => 'bloglines', 'BlogSearch' => 'blogsearch', 'PubSub' => 'pubsub', 'Syndic8' => 'syndic8', 'RadioUserland' => 'userland', 'Gigabot' => 'gigabot', 'Become.com' => 'become.com');
$useragent = $_SERVER['HTTP_USER_AGENT'];
foreach ($bots as $name => $lookfor) {
if (stristr($useragent, $lookfor) !== false) {
$should_count = false;
break;
}
}
}
if($should_count) {
if(defined('WP_CACHE') && WP_CACHE) {
echo "\n".''."\n";
wp_print_scripts(array('sack'));
echo ''."\n";
echo ''."\n";
} else {
if(!update_post_meta($id, 'views', ($post_views+1))) {
add_post_meta($id, 'views', 1, true);
}
}
}
}
}
### Function: Determine If Post Views Should Be Displayed (By: David Potter)
function should_views_be_displayed($views_options = null) {
if ($views_options == null) {
$views_options = get_option('views_options');
}
$display_option = 0;
if (is_home()) {
if (array_key_exists('display_home', $views_options)) {
$display_option = $views_options['display_home'];
}
} elseif (is_single()) {
if (array_key_exists('display_single', $views_options)) {
$display_option = $views_options['display_single'];
}
} elseif (is_page()) {
if (array_key_exists('display_page', $views_options)) {
$display_option = $views_options['display_page'];
}
} elseif (is_archive()) {
if (array_key_exists('display_archive', $views_options)) {
$display_option = $views_options['display_archive'];
}
} elseif (is_search()) {
if (array_key_exists('display_search', $views_options)) {
$display_option = $views_options['display_search'];
}
} else {
if (array_key_exists('display_other', $views_options)) {
$display_option = $views_options['display_other'];
}
}
return (($display_option == 0) || (($display_option == 1) && is_user_logged_in()));
}
### Function: Display The Post Views
function the_views($display = true, $prefix = '', $postfix = '', $always = false) {
$post_views = intval(post_custom('views'));
$views_options = get_option('views_options');
if ($always || should_views_be_displayed($views_options)) {
$output = $prefix.str_replace('%VIEW_COUNT%', number_format_i18n($post_views), $views_options['template']).$postfix;
if($display) {
echo apply_filters('the_views', $output);
} else {
return apply_filters('the_views', $output);
}
}
elseif (!$display) {
return '';
}
}
### Function: Display Least Viewed Page/Post
if(!function_exists('get_least_viewed')) {
function get_least_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
global $wpdb, $post;
$views_options = get_option('views_options');
$where = '';
$temp = '';
$output = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$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");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_views = intval($post->views);
$post_title = get_the_title();
$post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password);
$post_content = get_the_content();
if($chars > 0) {
$temp = "
".snippet_text($post_title, $chars)." - ".sprintf(__ngettext('%s view', '%s views', $post_views, 'wp-postviews'), number_format_i18n($post_views))."\n";
} else {
$temp = stripslashes($views_options['most_viewed_template']);
$temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
$temp = str_replace("%POST_TITLE%", $post_title, $temp);
$temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
$temp = str_replace("%POST_CONTENT%", $post_content, $temp);
$temp = str_replace("%POST_URL%", get_permalink(), $temp);
}
$output .= $temp;
}
} else {
$output = ''.__('N/A', 'wp-postviews').''."\n";
}
if($display) {
echo $output;
} else {
return $output;
}
}
}
### Function: Display Most Viewed Page/Post
if(!function_exists('get_most_viewed')) {
function get_most_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
global $wpdb, $post;
$views_options = get_option('views_options');
$where = '';
$temp = '';
$output = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$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");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_views = intval($post->views);
$post_title = get_the_title();
$post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password);
$post_content = get_the_content();
if($chars > 0) {
$temp = "".snippet_text($post_title, $chars)." - ".sprintf(__ngettext('%s view', '%s views', $post_views, 'wp-postviews'), number_format_i18n($post_views))."\n";
} else {
$temp = stripslashes($views_options['most_viewed_template']);
$temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
$temp = str_replace("%POST_TITLE%", $post_title, $temp);
$temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
$temp = str_replace("%POST_CONTENT%", $post_content, $temp);
$temp = str_replace("%POST_URL%", get_permalink(), $temp);
}
$output .= $temp;
}
} else {
$output = ''.__('N/A', 'wp-postviews').''."\n";
}
if($display) {
echo $output;
} else {
return $output;
}
}
}
### Function: Display Leased Viewed Page/Post By Category ID
if(!function_exists('get_least_viewed_category')) {
function get_least_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
global $wpdb, $post;
$views_options = get_option('views_options');
$where = '';
$temp = '';
$output = '';
if(is_array($category_id)) {
$category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
} else {
$category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
}
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$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");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_views = intval($post->views);
$post_title = get_the_title();
$post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password);
$post_content = get_the_content();
if($chars > 0) {
$temp = "".snippet_text($post_title, $chars)." - ".sprintf(__ngettext('%s view', '%s views', $post_views, 'wp-postviews'), number_format_i18n($post_views))."\n";
} else {
$temp = stripslashes($views_options['most_viewed_template']);
$temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
$temp = str_replace("%POST_TITLE%", $post_title, $temp);
$temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
$temp = str_replace("%POST_CONTENT%", $post_content, $temp);
$temp = str_replace("%POST_URL%", get_permalink(), $temp);
}
$output .= $temp;
}
} else {
$output = ''.__('N/A', 'wp-postviews').''."\n";
}
if($display) {
echo $output;
} else {
return $output;
}
}
}
### Function: Display Most Viewed Page/Post By Category ID
if(!function_exists('get_most_viewed_category')) {
function get_most_viewed_category($category_id = 0, $mode = '', $limit = 10, $chars = 0, $display = true) {
global $wpdb, $post;
$views_options = get_option('views_options');
$where = '';
$temp = '';
$output = '';
if(is_array($category_id)) {
$category_sql = "$wpdb->term_taxonomy.term_id IN (".join(',', $category_id).')';
} else {
$category_sql = "$wpdb->term_taxonomy.term_id = $category_id";
}
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$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");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_views = intval($post->views);
$post_title = get_the_title();
$post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password);
$post_content = get_the_content();
if($chars > 0) {
$temp = "".snippet_text($post_title, $chars)." - ".sprintf(__ngettext('%s view', '%s views', $post_views, 'wp-postviews'), number_format_i18n($post_views))."\n";
} else {
$temp = stripslashes($views_options['most_viewed_template']);
$temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
$temp = str_replace("%POST_TITLE%", $post_title, $temp);
$temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
$temp = str_replace("%POST_CONTENT%", $post_content, $temp);
$temp = str_replace("%POST_URL%", get_permalink(), $temp);
}
$output .= $temp;
}
} else {
$output = ''.__('N/A', 'wp-postviews').''."\n";
}
if($display) {
echo $output;
} else {
return $output;
}
}
}
### Function: Display Total Views
if(!function_exists('get_totalviews')) {
function get_totalviews($display = true) {
global $wpdb;
$total_views = intval($wpdb->get_var("SELECT SUM(meta_value+0) FROM $wpdb->postmeta WHERE meta_key = 'views'"));
if($display) {
echo $total_views;
} else {
return $total_views;
}
}
}
### Function: Snippet Text
if(!function_exists('snippet_text')) {
function snippet_text($text, $length = 0) {
if (defined('MB_OVERLOAD_STRING')) {
$text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
if (mb_strlen($text) > $length) {
return htmlentities(mb_substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
} else {
return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
}
} else {
$text = @html_entity_decode($text, ENT_QUOTES, get_option('blog_charset'));
if (strlen($text) > $length) {
return htmlentities(substr($text,0,$length), ENT_COMPAT, get_option('blog_charset')).'...';
} else {
return htmlentities($text, ENT_COMPAT, get_option('blog_charset'));
}
}
}
}
### Function: Process Post Excerpt, For Some Reasons, The Default get_post_excerpt() Does Not Work As Expected
function views_post_excerpt($post_excerpt, $post_content, $post_password) {
if(!empty($post_password)) {
if(!isset($_COOKIE['wp-postpass_'.COOKIEHASH]) || $_COOKIE['wp-postpass_'.COOKIEHASH] != $post_password) {
return __('There is no excerpt because this is a protected post.', 'wp-postviews');
}
}
if(empty($post_excerpt)) {
return snippet_text(strip_tags($post_content), 200);
} else {
return $post_excerpt;
}
}
### Function: Modify Default WordPress Listing To Make It Sorted By Post Views
function views_fields($content) {
global $wpdb;
$content .= ", ($wpdb->postmeta.meta_value+0) AS views";
return $content;
}
function views_join($content) {
global $wpdb;
$content .= " LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID";
return $content;
}
function views_where($content) {
global $wpdb;
$content .= " AND $wpdb->postmeta.meta_key = 'views'";
return $content;
}
function views_orderby($content) {
$orderby = trim(addslashes(get_query_var('v_orderby')));
if(empty($orderby) || ($orderby != 'asc' && $orderby != 'desc')) {
$orderby = 'desc';
}
$content = " views $orderby";
return $content;
}
### Function: Add Views Custom Fields
add_action('publish_post', 'add_views_fields');
function add_views_fields($post_ID) {
global $wpdb;
add_post_meta($post_ID, 'views', 0, true);
}
### Function: Delete Views Custom Fields
add_action('delete_post', 'delete_views_fields');
function delete_views_fields($post_ID) {
global $wpdb;
delete_post_meta($post_ID, 'views');
}
### Function: Views Public Variables
add_filter('query_vars', 'views_variables');
function views_variables($public_query_vars) {
$public_query_vars[] = 'v_sortby';
$public_query_vars[] = 'v_orderby';
return $public_query_vars;
}
### Function: Sort Ratings Posts
add_action('pre_get_posts', 'views_sorting');
function views_sorting() {
if(get_query_var('v_sortby') == 'views') {
add_filter('posts_fields', 'views_fields');
add_filter('posts_join', 'views_join');
add_filter('posts_where', 'views_where');
add_filter('posts_orderby', 'views_orderby');
}
}
### Function: Plug Into WP-Stats
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')) {
add_filter('wp_stats_page_admin_plugins', 'postviews_page_admin_general_stats');
add_filter('wp_stats_page_admin_most', 'postviews_page_admin_most_stats');
add_filter('wp_stats_page_plugins', 'postviews_page_general_stats');
add_filter('wp_stats_page_most', 'postviews_page_most_stats');
}
### Function: Add WP-PostViews General Stats To WP-Stats Page Options
function postviews_page_admin_general_stats($content) {
$stats_display = get_option('stats_display');
if($stats_display['views'] == 1) {
$content .= '
'."\n";
} else {
$content .= '
'."\n";
}
return $content;
}
### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page Options
function postviews_page_admin_most_stats($content) {
$stats_display = get_option('stats_display');
$stats_mostlimit = intval(get_option('stats_mostlimit'));
if($stats_display['viewed_most'] == 1) {
$content .= '
'."\n";
} else {
$content .= '
'."\n";
}
return $content;
}
### Function: Add WP-PostViews General Stats To WP-Stats Page
function postviews_page_general_stats($content) {
$stats_display = get_option('stats_display');
if($stats_display['views'] == 1) {
$content .= ''.__('WP-PostViews', 'wp-postviews').'
'."\n";
$content .= ''."\n";
$content .= '- '.sprintf(__ngettext('%s view was generated.', '%s views were generated.', get_totalviews(false), 'wp-postviews'), number_format_i18n(get_totalviews(false))).'
'."\n";
$content .= '
'."\n";
}
return $content;
}
### Function: Add WP-PostViews Top Most/Highest Stats To WP-Stats Page
function postviews_page_most_stats($content) {
$stats_display = get_option('stats_display');
$stats_mostlimit = intval(get_option('stats_mostlimit'));
if($stats_display['viewed_most'] == 1) {
$content .= ''.sprintf(__ngettext('%s Most Viewed Post', '%s Most Viewed Posts', $stats_mostlimit, 'wp-postviews'), number_format_i18n($stats_mostlimit)).'
'."\n";
$content .= ''."\n";
$content .= get_most_viewed('post', $stats_mostlimit, 0, false);
$content .= '
'."\n";
}
return $content;
}
### Function: Increment Post Views
increment_views();
function increment_views() {
global $wpdb;
$post_id = intval($_GET['postviews_id']);
if($post_id > 0) {
$post_views = get_post_custom($post_id);
$post_views = intval($post_views['views'][0]);
if(!update_post_meta($post_id, 'views', ($post_views+1))) {
add_post_meta($post_id, 'views', 1, true);
}
}
}
### Function: Post Views Options
add_action('activate_wp-postviews/wp-postviews.php', 'views_init');
function views_init() {
postviews_textdomain();
// Add Options
$views_options = array();
$views_options['count'] = 1;
$views_options['exclude_bots'] = 0;
$views_options['display_home'] = 0;
$views_options['display_single'] = 0;
$views_options['display_page'] = 0;
$views_options['display_archive'] = 0;
$views_options['display_search'] = 0;
$views_options['display_other'] = 0;
$views_options['template'] = __('%VIEW_COUNT% views', 'wp-postviews');
$views_options['most_viewed_template'] = '%POST_TITLE% - %VIEW_COUNT% '.__('views', 'wp-postviews').'';
add_option('views_options', $views_options, 'Post Views Options');
}
?>