Browse: Home / Hooks /

learndash_quiz_check_answer

apply_filters( 'learndash_quiz_check_answer',  boolean $check_answer,  string $question_type,  string $answer,  array $correct_answers,  int $answer_index,  WpProQuiz_Model_Question $question_model )

Filters whether to check the answer of close type question.


Description #


Parameters #

$check_answer

(boolean) Whether to check the answer.

$question_type

(string) Type of the question.

$answer

(string) The answer given by user for the question.

$correct_answers

(array) An array of correct answers for the question.

$answer_index

(int) Answer index.

$question_model

(WpProQuiz_Model_Question) Question model object.


Source #

File: includes/quiz/ld-quiz-pro.php


Examples #

Note: Extended code example below not guaranteed, you may need to consult with a developer

 <?php
/**
 * Example usage for learndash_quiz_check_answer filter.
 */
add_filter(
	'learndash_quiz_check_answer',
	function ( $correct = false, $question_type = 'cloze_answer', $user_response = null, $correctData = null, $answerIndex = 0, $questionModel = null ) {

		// v2.5 added
		if ( $question_type == 'cloze_answer' ) {

			// Check if this is from a specific quiz ID
			if ( $questionModel->getQuizId() == 2 ) {

				// Check if this is from a specific question ID
				if ( $questionModel->getId() == 4 ) {

					// perform some logic to compare the $user_response to the array of $correctData items

					// As an example we are gettng the real answer data again from the quiz and perform out own compare logic.
					$answer_data = $questionModel->getAnswerData();
					if ( isset( $answer_data[0] ) ) {
						$q_answer_text = $answer_data[0]->getAnswer();
						if ( ! empty( $q_answer_text ) ) {
							// What will be returned in the $q_answers is an array of possible answers in the 'correct' node for this question element.
							// So if the answer string is '{[play][love][hate]}' then $q_answers[correct] will be an array with these values.

							// The 'false' argument to the function learndash_question_cloze_fetch_data prevents converting the answer texts to lowercase.
							$q_answers = learndash_question_cloze_fetch_data( $q_answer_text, false );
							if ( ( isset( $q_answers['correct'][ $answerIndex ] ) ) && ( ! empty( $q_answers['correct'][ $answerIndex ] ) ) ) {
								if ( ! in_array( $user_response, $q_answers['correct'][ $answerIndex ] ) ) {
									$correct = false;
								}
							}
						}
					}
				}
			}
		}

		// Always return $correct;
		return $correct;

	},
	10,
	6
);