Bird
Raised Fist0
Wordpressframework~20 mins

Request and response handling in Wordpress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WordPress REST API Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this WordPress REST API callback?
Consider this REST API endpoint callback in WordPress. What will the response contain when accessed?
Wordpress
<?php
add_action('rest_api_init', function () {
  register_rest_route('myplugin/v1', '/data', array(
    'methods' => 'GET',
    'callback' => function () {
      return new WP_REST_Response(array('message' => 'Hello World'), 200);
    },
  ));
});
AA PHP error because WP_REST_Response is undefined
BAn empty JSON object {} with HTTP status 404
CA plain text response 'Hello World' with HTTP status 200
D{"message":"Hello World"} with HTTP status 200
Attempts:
2 left
💡 Hint
WP_REST_Response formats the array as JSON with the given status code.
📝 Syntax
intermediate
2:00remaining
Which option correctly registers a POST REST API route in WordPress?
You want to create a REST API route that accepts POST requests at 'myplugin/v1/submit'. Which code snippet is correct?
Aregister_rest_route('myplugin/v1', '/submit', array('methods' => 'post', 'callback' => 'handle_submit'));
Bregister_rest_route('myplugin/v1', '/submit', array('methods' => 'POST', 'callback' => 'handle_submit'));
Cregister_rest_route('myplugin/v1', '/submit', array('methods' => ['GET', 'POST'], 'callback' => 'handle_submit'));
Dregister_rest_route('myplugin/v1', '/submit', array('method' => 'POST', 'callback' => 'handle_submit'));
Attempts:
2 left
💡 Hint
The key for HTTP verbs is 'methods' and it is case sensitive.
🔧 Debug
advanced
2:00remaining
Why does this REST API callback cause a 500 Internal Server Error?
Examine this callback code for a WordPress REST API route. Why does it cause a server error?
Wordpress
<?php
function my_callback(WP_REST_Request $request) {
  $param = $request->get_param('id');
  if (!$param) {
    return new WP_Error('no_id', 'ID parameter missing', array('status' => 400));
  }
  return array('id' => $param);
}

add_action('rest_api_init', function () {
  register_rest_route('myplugin/v1', '/item', array(
    'methods' => 'GET',
    'callback' => 'my_callback',
  ));
});
AThe callback returns an array instead of WP_REST_Response or WP_Error, causing the error.
BThe callback uses get_param() which is not a valid method of WP_REST_Request.
CThe callback returns WP_Error correctly, but the route is missing permission_callback causing 500 error.
DThe callback returns WP_Error and array correctly; the 500 error is caused by missing permission_callback.
Attempts:
2 left
💡 Hint
WordPress REST API requires permission_callback for routes unless explicitly allowed.
❓ state_output
advanced
2:00remaining
What is the HTTP status code returned by this REST API callback?
This callback returns a WP_Error with a custom status. What status code will the client receive?
Wordpress
<?php
function error_callback() {
  return new WP_Error('forbidden', 'You do not have access', array('status' => 403));
}

add_action('rest_api_init', function () {
  register_rest_route('myplugin/v1', '/secret', array(
    'methods' => 'GET',
    'callback' => 'error_callback',
    'permission_callback' => '__return_true',
  ));
});
A403 Forbidden
B200 OK
C500 Internal Server Error
D401 Unauthorized
Attempts:
2 left
💡 Hint
WP_Error with 'status' in data sets the HTTP status code.
🧠 Conceptual
expert
2:00remaining
Which statement about WordPress REST API request and response handling is TRUE?
Select the correct statement about how WordPress handles REST API requests and responses.
AReturning a plain array from a callback automatically converts it to JSON with status 200.
BAll REST API routes must have a permission_callback; otherwise, WordPress returns 403 Forbidden automatically.
CWP_REST_Response objects cannot set custom HTTP headers in the response.
DWP_Error objects returned from callbacks always cause a 500 Internal Server Error.
Attempts:
2 left
💡 Hint
Think about default behaviors for arrays and errors in WordPress REST API.

Practice

(1/5)
1. In WordPress, which superglobal variable is commonly used to access data sent via an HTTP POST request?
easy
A. $_REQUEST
B. $_POST
C. $_GET
D. $GLOBALS

Solution

  1. Step 1: Understand HTTP POST data handling

    Data sent by users through a POST request is stored in the $_POST superglobal in PHP.
  2. Step 2: Differentiate from other superglobals

    $_GET holds URL query parameters, $_REQUEST combines GET, POST, and COOKIE but is less specific, and $GLOBALS holds all global variables.
  3. Final Answer:

    $_POST -> Option B
  4. Quick Check:

    POST data = $_POST [OK]
Hint: POST data is always in $_POST superglobal [OK]
Common Mistakes:
  • Confusing $_GET with $_POST
  • Using $_REQUEST without knowing its mixed content
  • Assuming $GLOBALS holds request data
2. Which of the following is the correct way to send a JSON response in a WordPress REST API callback function?
easy
A. wp_send_json($data);
B. header('Content-Type: text/plain'); echo $data;
C. echo json_encode($data);
D. return new WP_REST_Response($data, 200);

Solution

  1. Step 1: Understand WordPress REST API callback requirements

    REST API callbacks should return a WP_REST_Response, array, or WP_Error. The framework handles headers, JSON encoding, and status.
  2. Step 2: Compare other options

    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.
  3. Final Answer:

    return new WP_REST_Response($data, 200); -> Option D
  4. Quick Check:

    Return WP_REST_Response [OK]
Hint: Return WP_REST_Response for REST API JSON response [OK]
Common Mistakes:
  • Using wp_send_json() (intended for AJAX handlers)
  • Using echo without proper headers and exit
  • Sending wrong content type header
3. Consider this WordPress REST API callback function:
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?
medium
A. 200
B. 404
C. 500
D. 302

Solution

  1. Step 1: Analyze the parameter check

    The function checks if id equals '42'. If yes, it returns an array with message 'Found'.
  2. Step 2: Understand default REST API response codes

    Returning an array results in a 200 OK status. Returning WP_Error sets the error status (404 here).
  3. Final Answer:

    200 -> Option A
  4. Quick Check:

    Valid data returns 200 OK [OK]
Hint: Array return = 200 OK; WP_Error return = error code [OK]
Common Mistakes:
  • Assuming WP_Error always returns 200
  • Confusing string '42' with integer 42
  • Ignoring default REST API status codes
4. You wrote this WordPress REST API endpoint callback:
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?
medium
A. The echo statement after wp_send_json_success() will never run
B. wp_send_json_success() does not send JSON
C. get_param() cannot retrieve 'data' parameter
D. Missing return statement causes error

Solution

  1. Step 1: Understand wp_send_json_success behavior

    This function sends JSON response and calls exit(), stopping further code execution.
  2. Step 2: Analyze code after wp_send_json_success

    The echo 'Done'; line is unreachable because the script exits before it.
  3. Final Answer:

    The echo statement after wp_send_json_success() will never run -> Option A
  4. Quick Check:

    wp_send_json_success() exits script [OK]
Hint: Code after wp_send_json_success() is unreachable [OK]
Common Mistakes:
  • Expecting code after wp_send_json_success() to run
  • Confusing get_param() usage
  • Thinking wp_send_json_success() returns data instead of exiting
5. You want to create a WordPress REST API endpoint that accepts a POST request with a JSON body containing a 'name' field. Which sequence correctly handles the request and sends a JSON response with a greeting message?
hard
A. Use $request->get_body_params()['name'] to get 'name', then return ['greeting' => 'Hello ' . $name].
B. Use $_POST['name'] directly, then echo JSON encoded greeting and exit.
C. Use $request->get_json_params()['name'] to get 'name', then return new WP_REST_Response(['greeting' => 'Hello ' . $name], 200).
D. Use file_get_contents('php://input') to read JSON body, then use wp_send_json() to send response.

Solution

  1. Step 1: Retrieve JSON body parameters properly

    In WordPress REST API, $request->get_json_params() safely parses JSON body data.
  2. Step 2: Return a proper REST response object

    Returning WP_REST_Response with data and status code is the recommended way to send structured responses.
  3. Step 3: Evaluate other options

    A uses 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.
  4. Final Answer:

    Use $request->get_json_params()['name'] and return WP_REST_Response -> Option C
  5. Quick Check:

    Use get_json_params() + WP_REST_Response for JSON POST [OK]
Hint: Use get_json_params() for JSON body in REST API [OK]
Common Mistakes:
  • Using $_POST or get_body_params for JSON body data
  • Not decoding JSON body properly
  • Returning raw arrays instead of WP_REST_Response
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard