Skip to content

Instantly share code, notes, and snippets.

@agusmu
Forked from khromov/spp.php
Last active August 18, 2019 16:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agusmu/3b4bc5cfdbbea7f694a5 to your computer and use it in GitHub Desktop.
Save agusmu/3b4bc5cfdbbea7f694a5 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Simple Popular Posts Lite
Plugin URI: -
Description: -
Version: 2014.10.16
Author: khromov
Author URI: http://snippets.khromov.se
License: GPL2
*/
/**
* Class Simple_Popular_Posts
*/
class Simple_Popular_Posts
{
public static $td = 'spp';
public static $post_types = array('post'); //,'page'
/**
* Constructor sets up all our hooks
*/
function __construct()
{
add_action('wp_footer', array(&$this, 'footer_script'), 999);
add_filter('query_vars', array(&$this, 'query_vars'));
add_action('wp', array(&$this, 'count'));
}
/**
* Adds counting code to footer
*/
function footer_script()
{
if((is_single() || is_attachment() || is_page() || is_singular()) && in_array(get_post_type(get_the_ID()), $this::$post_types)) :
?>
<script type="text/javascript">
function SimplePopularPosts_AddCount(id, endpoint)
{
var xmlhttp;
var params = "/?spp_count=1&spp_post_id=" + id + "&cachebuster=" + Math.floor((Math.random() * 100000));
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", endpoint + params, true);
xmlhttp.send();
}
SimplePopularPosts_AddCount(<?php echo get_the_ID(); ?>, '<?php echo get_site_url(); ?>');
</script>
<?php
endif;
}
/**
* Adds our special query var
*/
function query_vars($query_vars)
{
$query_vars[] = 'spp_count';
return $query_vars;
}
/**
* Count function
*
* TODO: This should be doable with SHORTINIT and would be much faster
*/
function count()
{
/**
* Endpoint for counting visits
*/
if(intval(get_query_var('spp_count')) === 1 && intval(get_query_var('spp_post_id')) !== 0)
{
//JSON response
header('Content-Type: application/json');
$id = intval(get_query_var('spp_post_id'));
$current_count = get_post_meta($id, '_spp_count', true);
if($current_count === '')
$count = 1;
else
$count = intval($current_count)+1;
//Update post meta
update_post_meta($id, '_spp_count', $count);
echo json_encode(array('status' => 'OK', 'visits' => intval($current_count)+1));
}
}
}
$simple_popular_posts = new Simple_Popular_Posts();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment