Hey,
Actually haven’t inserted any big code – just tried getting the current user in function ‘vote’.
/**
* Compute vote
* @param int $req['poll'] poll ID required
* @param int $req['choice'] poll answer choice required
* @todo: [$poll_choice - 1] is just a temp fix. maybe acf/settings/row_index_offset filter?
*/
public function vote($req) {
// params vars
$poll_id = $req['poll'];
$poll_choice = (int) $req['choice'];
$poll_answers = get_field($this->field['answers'], $poll_id);
$poll_total = get_field($this->field['total'], $poll_id);
$poll_expired = get_field($this->field['expired'], $poll_id);
$poll_limit = get_field($this->field['limit_vote'], $poll_id);
// validate params from req
if (!is_numeric($poll_id) || !isset($poll_choice) || empty($poll_answers[$poll_choice - 1])) {
return new WP_Error('error', $this->message['invalid'], array('status' => 400));
}
if ($poll_expired || get_post_type($poll_id) != 'onyxpolls') {
return new WP_Error('error', $this->message['no_exist'], array('status' => 400));
}
if (isset($_COOKIE["onyx_poll_limit_$poll_id"]) && $poll_limit != 1) {
$response = array(
"code" => "not_allowed",
"id" => $poll_id,
"message" => $this->message['no_allowed'],
"voted" => false,
"data" => ["status" => 200]
);
} else {
// update vote fields
$add_vote = array(
"votes" => $poll_answers[$poll_choice - 1]['votes']+1
);
$row = update_row($this->field['answers'], $poll_choice, $add_vote, $poll_id);
$total = update_field($this->field['total'], $poll_total+1, $poll_id);
// set cookies
// limit = 1 (free vote)
// limit = 2 (per device/no expires)
$this->setcookie($poll_id, $poll_choice);
$user_id = get_current_user_id(); // RETURNS 0
// global $current_user;
//get_currentuserinfo();
//var_dump($current_user->ID);
/* when the POLL is answered get the current user ID in an repeater acf field which I've implemented in each post (poll) via acf */
/* I'm trying to LIMIT the submission to a USER - so not per defice - but poll per user */
$field_key = "field_5f220c11c3fc1"; // repeater field
$value = array('field_5f220c36c3fc2' => $user_id);
add_row($field_key, $value, $poll_id);
// do_action('acf/save_post', $poll_id);
// wp_redirect(add_query_arg('updated', 'success', wp_get_referer()));
// return reponse
$response = array(
"code" => ($row && $total) ? "success" : 'error',
"poll" => $poll_id,
"choice" => $poll_choice,
"message" => ($row && $total) ? $this->message['success'] : $this->message['error'],
"voted" => ($row && $total) ? true : false,
"data" => ["status" => 200]
);
}
$response += $this->poll_data($poll_id);
return new WP_REST_Response($response, 200);
}
Take a look at the comments. Tried to take the current user id with get_current_user_id() and it returns 0.
What I’m actually trying to do is to limit the poll per USER.
Thank you.