Performance: Request and response handling
This affects how quickly the server processes user requests and sends back responses, impacting page load speed and interactivity.
<?php // In functions.php add_action('init', function() { global $wpdb; if (isset($_GET['action']) && $_GET['action'] === 'load_data') { $cache_key = 'load_data_cache'; $data = get_transient($cache_key); if (!$data) { $data = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status = 'publish'"); set_transient($cache_key, $data, 3600); // Cache for 1 hour } echo json_encode($data); exit; } });
<?php // In functions.php add_action('init', function() { global $wpdb; if (isset($_GET['action']) && $_GET['action'] === 'load_data') { // Heavy database query without caching $data = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status = 'publish'"); echo json_encode($data); exit; } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy uncached DB query on every request | N/A (server-side) | N/A | Delays initial paint | [X] Bad |
| Cached DB query with transients | N/A (server-side) | N/A | Faster initial paint | [OK] Good |
$_POST superglobal in PHP.$_GET holds URL query parameters, $_REQUEST combines GET, POST, and COOKIE but is less specific, and $GLOBALS holds all global variables.$_POST -> Option B$_POST [OK]WP_REST_Response, array, or WP_Error. The framework handles headers, JSON encoding, and status.wp_send_json($data); sends JSON and exits with wp_die(), suitable for AJAX but bypasses REST processing/filters. echo json_encode($data); outputs JSON without headers or exit. header('Content-Type: text/plain'); echo $data; wrong type.function get_custom_data(\WP_REST_Request $request) {
$param = $request->get_param('id');
if ($param === '42') {
return ['message' => 'Found'];
}
return new WP_Error('not_found', 'ID not found', ['status' => 404]);
}
What will be the HTTP status code if the request URL includes ?id=42?id equals '42'. If yes, it returns an array with message 'Found'.function my_callback(\WP_REST_Request $request) {
$data = $request->get_param('data');
wp_send_json_success($data);
echo 'Done';
}
What is the problem with this code?echo 'Done'; line is unreachable because the script exits before it.$request->get_json_params() safely parses JSON body data.WP_REST_Response with data and status code is the recommended way to send structured responses.get_body_params() which checks form data ($_POST), empty for JSON body POSTs. C uses $_POST['name'] directly, same issue. D manually reads input bypassing framework helpers and uses wp_send_json() which exits.Pass the test and this pattern moves unknown