public function flag_answer() { if (!isset($_POST['wpnonce']) || !wp_verify_nonce(sanitize_text_field($_POST['wpnonce']), '_dwqa_action_flag_answer_nonce')) { wp_send_json_error(array('message' => __('Are you cheating huh?', 'dwqa'))); } if (!isset($_POST['answer_id'])) { wp_send_json_error(array('message' => __('Missing id of answer', 'dwqa'))); } global $current_user; $answer_id = intval($_POST['answer_id']); $flag = get_post_meta($answer_id, '_flag', true); if (!$flag) { $flag = array(); } else { $flag = unserialize($flag); } // _flag[ user_id => flag_bool , ...] $flag_score = 0; if (dwqa_is_user_flag($answer_id, $current_user->ID)) { //unflag $flag[$current_user->ID] = $flag_score = 0; } else { $flag[$current_user->ID] = $flag_score = 1; } $flag = serialize($flag); update_post_meta($answer_id, '_flag', $flag); wp_send_json_success(array('status' => $flag_score)); }
function dwqa_is_answer_flag($post_id) { if (dwqa_is_user_flag($post_id)) { return true; } else { $flag = get_post_meta($post_id, '_flag', true); if (empty($flag) || !is_array($flag)) { return false; } $flag = unserialize($flag); $flag_point = array_sum($flag); if ($flag_point > 5) { return true; } } return false; //showing }