Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Save Jetpack "Site Stats" Pageviews as Post Meta
<?php
/**
* Save Jetpack views as post meta: Process Ajax request
*
*/
add_action( 'wp_ajax_save_views', 'ac_ajax_save_views' );
add_action( 'wp_ajax_nopriv_save_views', 'ac_ajax_save_views' );
function ac_ajax_save_views() {
// Verify nonce
if ( ! wp_verify_nonce( $_POST['nonce'], 'ac-save-views-' . $_POST['post_id'] ) ) {
wp_die();
}
// Arguments for API call
// @link: https://stats.wordpress.com/csv.php
$args = array(
'days' => rand( 100 * 365, getrandmax() ), // To reliably bust cache: random number of days between 36,500 (~100 years in days) and max random number
'post_id' => $_POST['post_id'],
);
// Make API call
$stats = stats_get_csv( 'postviews', $args );
// Get current view count
$current_views = get_post_meta( $_POST['post_id'], 'views', true );
// Make sure new view count is greater than current view count (b/c if not, then something went wrong)
if ( isset( $stats[0]['views'] ) && (int) $stats[0]['views'] > (int) $current_views ) {
// Save views
update_post_meta( $_POST['post_id'], 'views', (int) $stats['0']['views'] );
}
// Set transient (so that we do not bombard the service w/ API calls)
set_transient( 'ac_view_counter_' . $_POST['post_id'], 1, 4 * HOUR_IN_SECONDS ); // Adjust transient time, if desired (here: 4 hours between API calls [which seems sensible])
wp_die(); // "this is required to terminate immediately and return a proper response"
}
<?php
/**
* Save Jetpack views as post meta: Enqueue script to trigger API call (via Ajax request)
*
*/
add_action( 'wp_enqueue_scripts', 'ac_enqueue_scripts_save_views' );
function ac_enqueue_scripts_save_views() {
// Bail: Not using Jetpack site stats
if ( ! function_exists( 'stats_get_csv' ) ) return;
// Bail: Not singular and specified post type(s)
$post_types = array(
'post', // Include other post types in array, if desired
);
if ( ! is_singular( $post_types ) ) return;
// Bail: Transient not expired
if ( false !== get_transient( 'ac_view_counter_' . get_the_ID() ) ) return;
// Script
wp_enqueue_script(
'ac-ajax-save-views',
get_stylesheet_directory_uri() . '/lib/js/ac.ajax-save-views.min.js', // Verify path to file
array( 'jquery' ),
CHILD_THEME_VERSION,
true
);
// Localization
$data = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'post_id' => get_the_ID(),
'nonce' => wp_create_nonce( 'ac-save-views-' . get_the_ID() ),
);
wp_localize_script( 'ac-ajax-save-views', 'save_views', $data );
}
jQuery(document).ready(function(e) {
e.ajax({
method: "POST",
url: save_views.ajax_url,
data: {
post_id: save_views.post_id,
nonce: save_views.nonce,
action: "save_views"
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.