AnsPress_Vote::vote()

Description #

Process voting button.

Changelog #

VersionDescription
2.0.1.1Introduced.

Source #

File: includes/votes.php

	public static function vote() {
		$post_id = (int) ap_sanitize_unslash( 'post_id', 'request' );

		if ( ! anspress_verify_nonce( 'vote_' . $post_id ) ) {
				ap_ajax_json( 'something_wrong' );
		}

		$type   = 'vote_up' === ap_sanitize_unslash( 'type', 'request' ) ? 'vote_up' : 'vote_down';
		$value  = 'vote_up' === $type ? '1' : '-1';
		$userid = get_current_user_id();
		$post   = ap_get_post( $post_id );
		$thing  = ap_user_can_vote_on_post( $post_id, $type, $userid, true );

		// Check if WP_Error object and send error message code.
		if ( is_wp_error( $thing ) ) {
			ap_ajax_json(
				array(
					'success'  => false,
					'snackbar' => array(
						'message' => $thing->get_error_message(),
					),
				)
			);
		}

		// Check if down vote disabled.
		if ( 'question' === $post->post_type && ap_opt( 'disable_down_vote_on_question' ) && 'vote_down' === $type ) {
			ap_ajax_json( 'voting_down_disabled' );
		} elseif ( 'answer' === $post->post_type && ap_opt( 'disable_down_vote_on_answer' ) && 'vote_down' === $type ) {
			ap_ajax_json( 'voting_down_disabled' );
		}

		$is_voted = ap_get_vote( $post_id, get_current_user_id(), 'vote' );

		if ( false !== $is_voted ) {

			// If user already voted and click that again then reverse.
			if ( $is_voted->vote_value == $value ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
				$counts = ap_delete_post_vote( $post_id, $userid, 'vote_up' === $type );
				ap_ajax_json(
					array(
						'success'   => true,
						'action'    => 'undo',
						'vote_type' => $type,
						'snackbar'  => array(
							'message' => __( 'Your vote has been removed.', 'anspress-question-answer' ),
						),
						'voteData'  => array(
							'net'    => $counts['votes_net'],
							'active' => '',
							'nonce'  => wp_create_nonce( 'vote_' . $post_id ),
						),
					)
				);
			}

			// Else ask user to undor their vote first.
			ap_ajax_json(
				array(
					'success'  => false,
					'snackbar' => array(
						'message' => __( 'Undo your vote first.', 'anspress-question-answer' ),
					),
					'voteData' => array(
						'active' => $type,
						'nonce'  => wp_create_nonce( 'vote_' . $post_id ),
					),
				)
			);
		}

		$counts = ap_add_post_vote( $post_id, $userid, 'vote_up' === $type );

		ap_ajax_json(
			array(
				'success'   => true,
				'action'    => 'voted',
				'vote_type' => $type,
				'snackbar'  => array(
					'message' => __( 'Thank you for voting.', 'anspress-question-answer' ),
				),
				'voteData'  => array(
					'net'    => $counts['votes_net'],
					'active' => $type,
					'nonce'  => wp_create_nonce( 'vote_' . $post_id ),
				),
			)
		);
	}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment