Home / Admin / Displaying WPForms Pro on Quiz and Survey Master Results Pages
Duplicate Snippet

Embed Snippet on Your Site

Displaying WPForms Pro on Quiz and Survey Master Results Pages

This code snippet will ensure WPForms Pro forms displays properly on QSM results pages.

<10
Code Preview
php
<?php
/**
 * WPForms QuizMaster Integration Standalone Snippet.
 */
add_action(
    'wpforms_loaded',
    function () {
		if ( ! class_exists( 'MLWQuizMasterNext' ) ) {
				return;
		}
		new WPForms_QuizMaster_Integration();
    }
);
class WPForms_QuizMaster_Integration {
	/**
	 * Constant representing the action to process a quiz.
	 */
	private const PROCESS_QUIZ_ACTION = 'qmn_process_quiz';
	/**
	 * Constructor - Initialize hooks.
	 */
	public function __construct() {
		$this->hooks();
	}
	/**
	 * Setup hooks.
	 */
	protected function hooks() {
		add_filter( 'wpforms_current_user_can', [ $this, 'allow_to_view_form' ], 10, 3 );
		add_filter( 'wpforms_frontend_form_action', [ $this, 'form_action_filter' ], 10, 2 );
		add_filter( 'qmn_end_quiz', [ $this, 'frontend_scripts' ], 10, 3 );
	}
	/**
	 * Allow viewing form during quiz processing.
	 */
	public function allow_to_view_form( $user_can, $caps, $id ) {
		$user_can = (bool) $user_can;
		if ( $user_can || ! $this->is_quiz_processing() ) {
			return $user_can;
		}
		return $caps === 'view_form_single';
	}
	/**
	 * Filter form action during quiz processing.
	 */
	public function form_action_filter( $action, $form_data ) {
		if ( $this->is_quiz_processing() ) {
			return '';
		}
		return (string) $action;
	}
	/**
	 * Add frontend scripts with inline JS.
	 */
	public function frontend_scripts( $value, $options, $quiz_data ) {
		if ( empty( $options->message_after ) ) {
			return (string) $value;
		}
		$this->enqueue_scripts_with_inline_js();
		return (string) $value;
	}
	/**
	 * Enqueue scripts with inline JS instead of separate file.
	 */
	private function enqueue_scripts_with_inline_js() {
		// Enqueue jQuery as dependency.
		wp_enqueue_script( 'jquery' );
		// Add inline script.
		$inline_js = "
		( function( document, window, $ ) {
			const app = {
				init: function() {
					$( app.ready );
				},
				ready: function() {
					if ( ! window.wpforms ) {
						return;
					}
					$( document ).on( 'qsm_after_quiz_submit', app.reInitWPForms );
				},
				reInitWPForms: function() {
					wpforms.init();
					if ( 'undefined' !== typeof wpformsRecaptchaLoad ) {
						wpformsRecaptchaLoad();
					}
					if ( 'undefined' !== typeof WPFormsRepeaterField ) {
						WPFormsRepeaterField.init();
					}
				}
			};
			app.init();
		}( document, window, jQuery ) );
		";
		wp_add_inline_script( 'jquery', $inline_js );
	}
	/**
	 * Check if quiz is being processed via AJAX.
	 */
	protected function is_quiz_processing() {
		if ( ! wp_doing_ajax() ) {
			return false;
		}
		$action = wp_unslash( $_POST['action'] ?? '' );
		return $action === self::PROCESS_QUIZ_ACTION;
	}
}

Comments

Add a Comment