Skip to content

Commit

Permalink
WIP Testing storage of counts in objects instead of individual paths
Browse files Browse the repository at this point in the history
  • Loading branch information
hs4man21 committed Nov 28, 2020
1 parent a621c19 commit 6ae201c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
6 changes: 2 additions & 4 deletions wp-admin/js/post.js
Expand Up @@ -284,10 +284,8 @@ window.wp = window.wp || {};
}(jQuery));

jQuery(document).ready( function($) {
var id = $('#post_ID').val();
console.log("Testing");
console.log(id);
$.get( "https://stanforddaily.com/wp-json/wp/v2/posts/" + id + "/views");
var id = $('#post_ID').val() || 0;
$.get( "https://stanforddaily.com/wp-json/wp/v2/views/" + id);
});

/**
Expand Down
19 changes: 14 additions & 5 deletions wp-includes/functions.php
Expand Up @@ -7167,7 +7167,7 @@ function is_php_version_compatible( $required ) {
}

add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2/posts/', '(?P<id>\d+)/views', array(
register_rest_route( 'wp/v2/views/', '(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'post_view_counter_function',
));
Expand All @@ -7178,9 +7178,18 @@ function post_view_counter_function( WP_REST_Request $request ) {
if ( FALSE === get_post_status( $post_id ) ) {
return new WP_Error( 'error_no_post', 'Not a post id', array( 'status' => 404 ) );
} else {
$current_views = get_post_meta( $post_id, 'views', true );
$views = $current_views + 1;
update_post_meta( $post_id, 'views', $views );
return $views;
$current_views = get_post_meta( $post_id, 'views', true );
if ( gettype($current_views) !== "object" ) {
$current_views = new stdClass();
}
$current_date = date("Y-m-d");
if (property_exists($current_views, $current_date)) {
$current_views[$current_date] = $current_views[$current_date] + 1;
update_post_meta( $post_id, 'views', $current_views );
} else {
$current_views[$current_date] = 1;
update_post_meta( $post_id, 'views', $current_views );
}
return $current_views;
}
}

0 comments on commit 6ae201c

Please sign in to comment.