Skip to content

Instantly share code, notes, and snippets.

@ideag
Last active January 3, 2018 13:24
Show Gist options
  • Save ideag/f975b57077384f9ca181a6fd391d9542 to your computer and use it in GitHub Desktop.
Save ideag/f975b57077384f9ca181a6fd391d9542 to your computer and use it in GitHub Desktop.
CA Pageviews
<?php
/**
* Plugin Name: CodeAcademy Pageviews
* Author: Arūnas Liuiza
* Version: 0.3.0
*
* @package CA_Pageview
* @version 0.3.0
*/
add_action( 'plugins_loaded', 'CA_Pageview' );
function CA_Pageview() {
if ( false === CA_PageviewClass::$instance ) {
CA_PageviewClass::$instance = new CA_PageviewClass();
}
return CA_PageviewClass::$instance;
}
class CA_PageviewClass {
public static $instance = false;
public $plugin_path = '';
public function __construct() {
$this->plugin_path = plugin_dir_path( __FILE__ );
add_action( 'wp', array( $this, 'count' ) );
add_filter( 'the_content', array( $this, 'display' ) );
add_action( 'rest_api_init', array( $this, 'api_field' ) );
add_action( 'rest_api_init', array( $this, 'api_endpoint' ) );
}
public function api_endpoint() {
register_rest_route(
'ca-pageview/v1',
'/top',
array(
'methods' => 'GET',
'callback' => array( $this, 'top' ),
)
);
}
public function top() {
global $wpdb;
$sql = "SELECT `post_id`, `meta_value` * 1 as `count`
FROM {$wpdb->postmeta}
WHERE `meta_key` = '_ca_pageview'
ORDER BY `count` DESC";
$result = $wpdb->get_results( $sql );
return $result;
}
public function api_field() {
register_rest_field(
'post',
'pageviews',
array(
'get_callback' => array( $this, 'get' ),
)
);
}
public function get( $post ) {
$post_id = $post['id'];
$count = get_post_meta( $post_id, '_ca_pageview', true );
return (int) $count;
}
public function count() {
if ( ! is_singular() ) {
return false;
}
$post_id = get_the_id();
$count = get_post_meta( $post_id, '_ca_pageview', true );
++$count;
update_post_meta( $post_id, '_ca_pageview', $count );
}
public function display( $content ) {
if ( ! is_singular() ) {
return $content;
}
$post_id = get_the_id();
$count = get_post_meta( $post_id, '_ca_pageview', true );
if ( ! $count ) {
$count = 0;
}
$display = _n(
'This post was viewed %s time.',
'This post was viewed %s times.',
$count,
'ca-pageview'
);
$display = sprintf( $display, $count );
$content .= PHP_EOL . PHP_EOL . $display;
return $content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment