Request and response handling lets your WordPress site talk to users and other systems. It helps you get data from visitors and send back the right information.
0
0
Request and response handling in Wordpress
Introduction
When you want to get data from a form submitted by a visitor.
When you need to send a custom message or data back to the browser.
When building a plugin that interacts with external APIs.
When creating custom REST API endpoints in WordPress.
When you want to handle AJAX requests on your site.
Syntax
Wordpress
<?php // Access request data $variable = $_GET['param'] ?? $_POST['param'] ?? null; // Send response wp_send_json_success($data); wp_send_json_error($error_message); // Register REST API endpoint add_action('rest_api_init', function () { register_rest_route('namespace/v1', '/route', [ 'methods' => 'GET', 'callback' => 'your_callback_function', ]); });
Use $_GET and $_POST to get data sent by users.
Use wp_send_json_success() and wp_send_json_error() to send JSON responses easily.
Examples
This gets the 'name' from the URL and shows a greeting.
Wordpress
<?php // Get a value from URL query $name = $_GET['name'] ?? 'Guest'; echo 'Hello, ' . esc_html($name);
This sends a JSON response with a success message.
Wordpress
<?php // Send JSON success response $data = ['message' => 'Success!']; wp_send_json_success($data);
This creates a custom REST API endpoint that returns a greeting.
Wordpress
<?php // Register a REST API endpoint add_action('rest_api_init', function () { register_rest_route('myplugin/v1', '/hello', [ 'methods' => 'GET', 'callback' => function () { return ['greeting' => 'Hello from REST API']; }, ]); });
Sample Program
This plugin adds a simple form using a shortcode. When the form is submitted, it reads the name and shows a greeting.
Wordpress
<?php /* Plugin Name: Simple Request Response Demo */ // Handle form submission add_action('init', function () { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_name'])) { $name = sanitize_text_field($_POST['user_name']); // Store name in session or do something echo 'Hello, ' . esc_html($name) . '!'; exit; } }); // Add a shortcode to show a form add_shortcode('name_form', function () { return '<form method="POST"> <label for="user_name">Enter your name:</label> <input type="text" id="user_name" name="user_name" required> <button type="submit">Submit</button> </form>'; });
OutputSuccess
Important Notes
Always sanitize and validate user input to keep your site safe.
Use WordPress functions like esc_html() to safely show data.
For AJAX or REST API, use proper hooks and return data in JSON format.
Summary
Request handling means getting data users send to your site.
Response handling means sending back messages or data to users.
WordPress offers simple ways to handle both with PHP and REST API.