AnsPress_Ajax::toggle_best_answer()

Description #

Ajax action for selecting a best answer.

Changelog #

VersionDescription
4.1.6Check if user have permission to toggle best answer.
4.1.2Log activities to ap_activity table and removed @see ap_update_post_activity_meta().
2.0.0Introduced.

Source #

File: includes/ajax-hooks.php

	public static function toggle_best_answer() {
		$answer_id = (int) ap_sanitize_unslash( 'answer_id', 'r' );

		if ( ! is_user_logged_in() || ! check_ajax_referer( 'select-answer-' . $answer_id, 'nonce', false ) ) {
			ap_ajax_json( 'something_wrong' );
		}

		$_post = ap_get_post( $answer_id );

		// Check for permission.
		if ( ! ap_user_can_select_answer( $_post ) ) {
			ap_ajax_json( array(
				'success'    => false,
				'snackbar' 	 => [ 'message' => __( 'You do not have permission to select or unselect answer', 'anspress-question-answer' ) ],
			) );
		}

		// Unselect best answer if already selected.
		if ( ap_have_answer_selected( $_post->post_parent ) ) {
			ap_unset_selected_answer( $_post->post_parent );

			/**
			 * Action triggered after an answer is un-selected as best.
			 *
			 * @param WP_Post $_post WordPress post object.
			 * @since unknown
			 */
			do_action( 'ap_unselect_answer', $_post );

			ap_ajax_json( array(
				'success'    => true,
				'action'     => 'unselected',
				'snackbar' 	 => [ 'message' => __( 'Best answer is unselected for your question.', 'anspress-question-answer' ) ],
				'label'      => __( 'Select', 'anspress-question-answer' ),
			) );
		}

		// Do not allow answer to be selected as best if status is moderate.
		if ( 'moderate' === $_post->post_status || 'trash' === $_post->post_status || 'private' === $_post->post_status ) {
			ap_ajax_json( [
				'success'  => false,
				'snackbar' => [ 'message' => __( 'This answer cannot be selected as best, update status to select as best answer.', 'anspress-question-answer' ) ],
			] );
		}

		/**
		 * Trigger right after selecting an answer.
		 *
		 * @param object $_post Post.
		 */
		do_action( 'ap_select_answer', $_post );

		// Update question qameta.
		ap_set_selected_answer( $_post->post_parent, $_post->ID );

		// Close question if enabled in option.
		if ( ap_opt( 'close_selected' ) ) {
			ap_insert_qameta( $_post->post_parent, [ 'closed' => 1 ] );
		}

		ap_ajax_json( array(
			'success'  => true,
			'action'   => 'selected',
			'snackbar' => [ 'message' => __( 'Best answer is selected for your question.', 'anspress-question-answer' ) ],
			'label'    => __( 'Unselect', 'anspress-question-answer' ),
		) );
	}

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