learndash_quiz_check_answer

apply_filters( 'learndash_quiz_check_answer',  boolean $check_answer,  string $queston_type,  string $answer,  array $correct_answers,  WpProQuiz_Model_Question $question_model )

Filters whether to check the answer of cloze type question.


Description #


Parameters #

$check_answer

(boolean) Whether to check the answer.

$queston_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.

$question_model

(WpProQuiz_Model_Question) Question model object.


Source #

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


Examples #

 <?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 fetchQuestionCloze prevents converting the answer texts to lowercase.
							$q_answers = fetchQuestionCloze( $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
);