Guide to How to build a custom quiz to practice coding and math with Artificial Intelligence
How to Build a Custom Quiz to Practice Coding and Math with Artificial Intelligence
Welcome to the ultimate tutorial guide. You will learn, step by step, how to create an AI‑powered quiz that generates coding and math problems on demand, records answers, and provides instant feedback—all within a WordPress site.
- A fully functional WordPress plugin that renders a sleek quiz interface.
- Integration with OpenAI’s API (or a local LLM) to generate fresh questions.
- Secure storage of user responses using the WordPress database.
- Real‑time grading for code snippets and math equations.
Prerequisites
- WordPress ≥ 5.9 with admin access.
- Basic knowledge of PHP, JavaScript, and HTML/CSS.
- An OpenAI API key (or any LLM endpoint you prefer).
- Node.js (optional) for local testing of the AI prompt.
Step 1 – Set Up a Development Environment
1. Create a new folder ai-quiz inside wp-content/plugins.
2. Inside the folder, add a starter file ai-quiz.php and a sub‑folder assets for CSS/JS.
3. Activate the plugin from the WordPress admin dashboard.
Step 2 – Design the Data Schema
We store each quiz attempt in a custom table wp_ai_quiz_attempts. Run the following SQL once (e.g., via dbDelta on plugin activation):
CREATE TABLE wp_ai_quiz_attempts (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT(20) UNSIGNED NOT NULL,
question LONGTEXT NOT NULL,
answer LONGTEXT NOT NULL,
correct BOOLEAN NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Use WPDB to insert and retrieve records safely.
Step 3 – Build the AI Question Generator
We call the OpenAI /v1/chat/completions endpoint to produce a question based on a simple system prompt.
function ai_quiz_generate_question($type = 'coding') {
$api_key = defined('OPENAI_API_KEY') ? OPENAI_API_KEY : '';
$prompt = $type === 'math'
? "Generate a single‑step algebra problem with a numeric answer."
: "Create a short JavaScript coding challenge that asks the user to write a function solving a specific problem.";
$body = [
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => $prompt],
],
'max_tokens' => 200,
];
$response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode($body),
'timeout' => 30,
]);
if (is_wp_error($response)) return false;
$data = json_decode(wp_remote_retrieve_body($response), true);
return $data['choices'][0]['message']['content'] ?? false;
}
Store the generated question in a transient (cache) for 5 minutes to avoid repeated API calls.
Step 4 – Create the Quiz UI with a Gutenberg Block
Register a dynamic block that renders the question and a submission form.
function ai_quiz_register_block() {
wp_register_script(
'ai-quiz-block',
plugins_url('assets/block.js', __FILE__),
['wp-blocks', 'wp-element', 'wp-i18n', 'wp-editor'],
filemtime(plugin_dir_path(__FILE__) . 'assets/block.js')
);
register_block_type('ai-quiz/interactive', [
'editor_script' => 'ai-quiz-block',
'render_callback' => 'ai_quiz_render_block',
]);
}
add_action('init', 'ai_quiz_register_block');
function ai_quiz_render_block($attributes) {
$type = $attributes['type'] ?? 'coding';
$question = ai_quiz_generate_question($type);
ob_start(); ?>
Your Question
The accompanying block.js handles the AJAX call to evaluate the answer.
Step 5 – Evaluate Answers Server‑Side
function ai_quiz_evaluate_answer() {
if (!isset($_POST['answer'], $_POST['question'])) wp_send_json_error('Missing data');
$user_answer = sanitize_textarea_field($_POST['answer']);
$question = wp_kses_post($_POST['question']);
$type = sanitize_key($_POST['type']);
// Simple evaluation for math: compare numeric values
if ($type === 'math') {
preg_match('/\d+(\.\d+)?/', $question, $matches);
$expected = $matches[0] ?? null;
$correct = $expected && abs(floatval($expected) - floatval($user_answer)) < 0.001;
} else {
// For coding, we run the code in a sandboxed container (example using eval)
$correct = false; // placeholder – implement your own sandbox for safety
}
// Save attempt
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'ai_quiz_attempts',
[
'user_id' => get_current_user_id(),
'question' => $question,
'answer' => $user_answer,
'correct' => $correct ? 1 : 0,
],
['%d', '%s', '%s', '%d']
);
wp_send_json_success(['correct' => $correct, 'expected' => $expected ?? null]);
}
add_action('wp_ajax_ai_quiz_evaluate', 'ai_quiz_evaluate_answer');
add_action('wp_ajax_nopriv_ai_quiz_evaluate', 'ai_quiz_evaluate_answer');
Step 6 – Add Front‑End Interactivity
// assets/script.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.ai-quiz-form').forEach(function (form) {
form.addEventListener('submit', function (e) {
e.preventDefault();
const answer = form.querySelector('[name="answer"]').value;
const type = form.dataset.type;
const question = form.parentElement.querySelector('p').innerText;
const data = new FormData();
data.append('action', 'ai_quiz_evaluate');
data.append('answer', answer);
data.append('question', question);
data.append('type', type);
fetch(ajaxurl, {
method: 'POST',
credentials: 'same-origin',
body: data,
})
.then(r => r.json())
.then(res => {
const resultDiv = form.parentElement.querySelector('.ai-quiz-result');
if (res.success) {
resultDiv.style.display = 'block';
if (res.data.correct) {
resultDiv.innerHTML = 'Correct! 🎉';
} else {
const exp = res.data.expected ? `
Expected answer: ${res.data.expected}` : '';
resultDiv.innerHTML = `Incorrect.${exp}`;
}
} else {
resultDiv.textContent = 'Error evaluating answer.';
}
});
});
});
});
Step 7 – Polish the Design (Glass‑morphic Callout & Cards)
Use the .callout class already defined in the style block to highlight tips, examples, or warnings. The .card class gives every section a subtle elevation and hover animation, keeping the UI modern and engaging.
Step 8 – Test and Deploy
| Task | How to Verify |
|---|---|
| API Connection | Check that a question appears without errors. |
| Answer Evaluation | Submit a known correct answer and see the “Correct!” badge. |
| Database Logging | Look at wp_ai_quiz_attempts for a new row after each submit. |
| Responsive Design | Resize the browser; cards should adjust fluidly. |
Conclusion
You now have a fully functional AI‑driven quiz that can generate fresh coding and math challenges, capture user answers, and deliver instant feedback—all built with WordPress standards and styled in a clean, olive‑green palette. Extend the project by adding more question types, integrating a code‑execution sandbox, or tracking user progress with leaderboards. Happy coding, and let the AI keep your quizzes unpredictable and engaging!
Comments
Post a Comment