Created
February 6, 2018 04:32
-
-
Save jpjuliao/e64cf990e77936d21b4820942c6e7cec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( !defined('ABSPATH') ) exit(); | |
/** | |
* Plugin name: Post View Tracker | |
* Plugin URI: http://jpjuliao.com/ | |
* Description: Track and order by post views in woocommerce. | |
* Version: 1.0 | |
* Author: Juan Pablo Juliao | |
* Author URI: https://jpjuliao.com | |
* Text Domain: jpjuliao-post-view-tracker | |
*/ | |
class JpjuliaoPostViewsTracker { | |
public $count_key = 'post_views_count'; | |
function __construct() { | |
add_action('template_redirect', array($this, 'setPostViews') ); | |
add_filter( 'woocommerce_get_catalog_ordering_args', array($this, 'woocommerce_get_catalog_ordering_args') ); | |
add_filter( 'woocommerce_default_catalog_orderby_options', array($this, 'woocommerce_catalog_orderby') ); | |
add_filter( 'woocommerce_catalog_orderby', array($this, 'woocommerce_catalog_orderby') ); | |
// Remove issues with prefetching adding extra views | |
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); | |
} | |
function woocommerce_get_catalog_ordering_args( $args ) { | |
$orderby_value = isset( $_GET['orderby'] ) | |
? woocommerce_clean( $_GET['orderby'] ) | |
: apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ); | |
if ( 'views' == $orderby_value ) { | |
$args['orderby'] = 'meta_value_num'; | |
$args['order'] = ''; | |
$args['meta_key'] = $this->count_key; | |
} | |
return $args; | |
} | |
function woocommerce_catalog_orderby( $sortby ) { | |
$sortby['views'] = 'Views'; | |
return $sortby; | |
} | |
function getPostViews($postID){ | |
$count_key = $this->count_key; | |
$count = get_post_meta($postID, $count_key, true); | |
if($count==''){ | |
$count = 0; | |
delete_post_meta($postID, $count_key); | |
add_post_meta($postID, $count_key, '0'); | |
} | |
return printf( _n( '%s view', '%s views', $count, 'jpjuliao-post-view-tracker' ), number_format_i18n( $count ) ); | |
} | |
function setPostViews() { | |
global $post; | |
$postID = $post->ID; | |
$count_key = $this->count_key; | |
$count = get_post_meta($postID, $count_key, true); | |
if($count==''){ | |
$count = 0; | |
delete_post_meta($postID, $count_key); | |
add_post_meta($postID, $count_key, '0'); | |
}else{ | |
$count++; | |
update_post_meta($postID, $count_key, $count); | |
} | |
} | |
} | |
new JpjuliaoPostViewsTracker(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment