Skip to content

Instantly share code, notes, and snippets.

@Fobiya
Created June 19, 2020 16:18
Show Gist options
  • Save Fobiya/a79534679fbf55a7abddbb90e4c8a31f to your computer and use it in GitHub Desktop.
Save Fobiya/a79534679fbf55a7abddbb90e4c8a31f to your computer and use it in GitHub Desktop.
rest_api_init add input
rest_api_init add input
/wp-json/wp/v2/blog/33393?&_embed
/**** getPostViews ****/
function getPostViews($postID)
{
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if ($count == '') {
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 views";
}
return $count . ' views';
}
function setPostViews($postID)
{
$count_key = 'post_views_count';
$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);
}
}
/**** getPostViews ****/
add_action( 'rest_api_init', function(){
register_rest_field( 'blog', 'post_views_count', array( // blog catygory
'get_callback' => function( $post, $field_name, $request ){
return getPostViews($post['id']);
},
'update_callback' => null,
'schema' => null
) );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment