Adding view counter to wordpress rest api

This snippet of code will add a view counter to your wordpress rest api, making the value available in the meta->post_views field for future use.

 * Updates the post meta with a views counter
function my_react_rest_prepare_post($response) {
    if (!isset($response->data) && isset($response->data['type'])) return $response;
    if ($response->data['type'] == 'post') return $response;
    $id = intval($response->data['id']);
    $views = get_post_meta($id, 'post_views', true);
    if (!$views) {
        add_post_meta($id, 'post_views', 1);
    } else {
        update_post_meta($id, 'post_views', intval($views) + 1);
    return $response;


Leave a Reply

Your email address will not be published.