Skip to content

Instantly share code, notes, and snippets.

@bravokeyl
Last active April 10, 2018 07:09
Show Gist options
  • Save bravokeyl/910312159e645057e6f52fae442042b1 to your computer and use it in GitHub Desktop.
Save bravokeyl/910312159e645057e6f52fae442042b1 to your computer and use it in GitHub Desktop.
WP Votes counter using rest api
<?php
/*
Update post meta based on the action taken on the post
*/
function mubit_update_votes($id, $key, $action) {
$data = array();
if(empty($id) || empty($action) || empty($key)) {
return $data;
}
$votes = get_post_meta($id, $key, true);
if(empty($votes)) {
update_post_meta($id, $key, 1);
$data[$action] = 1;
} else {
$votes = intval($votes) + 1;
update_post_meta($id, $key, $votes);
$data[$action] = $votes;
}
return $data;
}
/*
Votes Callback
Verifying the nonce passed in the post boday `mu`
*/
function mubit_votes_post_cb( $request ) {
$data = array();
$params = $request->get_params();
$nonce_verify = wp_verify_nonce( $params['mu'], 'wp_rest' );
if(!$nonce_verify) {
return new WP_Error( 'code', __( 'Request origin error.', 'nysw' ) );
}
$id = $params['id'];
$action = $params['action'];
if(isset($params) && isset($id) && intval($id)
&& isset($action) && !empty($action)) {
$id = intval($id);
if($action === 'upvotes'){
$data = mubit_update_votes($id, '_bk_upvote_count', $action);
} elseif($action === 'downvotes'){
$data = mubit_update_votes($id, '_bk_downvote_count', $action);
}
$res = wp_send_json($data);
return new WP_REST_Response( $res, 200 );
} else {
return new WP_Error( 'code', __( 'Error performing an action.', 'nysw' ) );
}
return null;
}
/*
Adds a custom route `mubit/v1` with one endpoint `votes`
*/
function mubit_custom_route() {
register_rest_route( 'mubit/v1', '/votes/(?P<id>\d+)',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'mubit_votes_post_cb',
)
);
}
add_action( 'rest_api_init', 'mubit_custom_route');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment