Bird
Raised Fist0
Wordpressframework~10 mins

Custom endpoint registration in Wordpress - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom endpoint registration
Start WordPress Init
↓
Hook into 'rest_api_init'
↓
Call register_rest_route()
↓
Define endpoint path & methods
↓
Assign callback function
↓
Endpoint ready to handle requests
↓
Client sends request
↓
Callback runs, returns response
↓
Response sent back to client
WordPress hooks into initialization, registers a REST API endpoint with a path, methods, and callback, then handles requests by running the callback and returning the response.
Execution Sample
Wordpress
<?php
add_action('rest_api_init', function () {
  register_rest_route('myplugin/v1', '/data', [
    'methods' => 'GET',
    'callback' => 'myplugin_get_data',
  ]);
});

function myplugin_get_data() {
  return ['message' => 'Hello from custom endpoint'];
}
Registers a GET endpoint at /wp-json/myplugin/v1/data that returns a simple message.
Execution Table
StepActionFunction CalledParametersResult
1WordPress initializes REST APIadd_action'rest_api_init', callbackCallback registered for REST API init
2REST API initializesrest_api_init hook firesnoneCallback runs
3Register endpointregister_rest_route'myplugin/v1', '/data', argsEndpoint registered at /myplugin/v1/data with GET method
4Client sends GET requestN/AGET /wp-json/myplugin/v1/dataRequest received
5Run callbackmyplugin_get_datanoneReturns ['message' => 'Hello from custom endpoint']
6Send responseN/AResponse JSONClient receives JSON message
7EndN/AN/ARequest complete
💡 Request completes after callback returns response and client receives it
Variable Tracker
VariableStartAfter Step 3After Step 5Final
registered_endpointsemptycontains /myplugin/v1/data GET endpointunchangedunchanged
requestnonenoneGET /wp-json/myplugin/v1/dataprocessed
responsenonenone['message' => 'Hello from custom endpoint']sent to client
Key Moments - 2 Insights
Why do we hook into 'rest_api_init' instead of 'init' to register endpoints?
Because 'rest_api_init' runs specifically when the REST API is ready to register routes, ensuring endpoints are registered at the right time. See execution_table step 2 and 3.
What happens if the callback function is missing or returns nothing?
The endpoint will respond with an empty or error response, so the callback must return valid data. See execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the endpoint actually registered?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Check the 'Action' and 'Result' columns in step 3 for endpoint registration
According to variable_tracker, what is the state of 'response' after step 5?
AEmpty
BContains the callback return data
CContains the client request
DNot defined yet
💡 Hint
Look at the 'response' row under 'After Step 5' column
If the client sends a POST request instead of GET, what happens based on the execution flow?
AEndpoint rejects request (method not allowed)
BCallback runs normally
CEndpoint registers a new POST route automatically
DWordPress crashes
💡 Hint
The registered endpoint only allows GET method as per step 3 parameters
Concept Snapshot
Custom endpoint registration in WordPress:
- Hook into 'rest_api_init'
- Use register_rest_route(namespace, route, args)
- Args include 'methods' and 'callback'
- Callback returns data for response
- Endpoint accessible at /wp-json/namespace/route
- Only registered methods accepted
Full Transcript
This visual execution trace shows how WordPress registers a custom REST API endpoint. First, WordPress hooks a function to 'rest_api_init' which runs when the REST API initializes. Inside this function, register_rest_route is called with a namespace, route path, and arguments including HTTP methods and a callback function. This registers the endpoint so WordPress knows to listen for requests at that URL. When a client sends a GET request to the endpoint, WordPress runs the callback function, which returns data. WordPress then sends this data back as a JSON response to the client. Variables like registered_endpoints, request, and response change state during these steps. Key moments include understanding why 'rest_api_init' is used and the importance of the callback returning data. The quiz tests knowledge of when registration happens, response content, and method restrictions.

Practice

(1/5)
1. What is the main purpose of using add_rewrite_endpoint in WordPress?
easy
A. To enqueue styles and scripts
B. To register a new plugin in WordPress
C. To add a new URL part (endpoint) for custom content or actions
D. To create a new database table

Solution

  1. Step 1: Understand the function purpose

    add_rewrite_endpoint is used to add new URL parts to WordPress URLs.
  2. Step 2: Identify correct usage context

    This function helps create custom endpoints for special content or actions, not for plugins, tables, or scripts.
  3. Final Answer:

    To add a new URL part (endpoint) for custom content or actions -> Option C
  4. Quick Check:

    add_rewrite_endpoint adds URL parts = D [OK]
Hint: Endpoints add URL parts for custom content [OK]
Common Mistakes:
  • Confusing endpoints with plugin registration
  • Thinking it creates database tables
  • Assuming it loads scripts or styles
2. Which hook is the correct place to call add_rewrite_endpoint when registering a custom endpoint?
easy
A. wp_footer
B. wp_enqueue_scripts
C. admin_menu
D. init

Solution

  1. Step 1: Recall WordPress hook usage

    The init hook runs early and is the recommended place to add rewrite rules and endpoints.
  2. Step 2: Eliminate incorrect hooks

    wp_enqueue_scripts is for scripts/styles, admin_menu is for admin menus, and wp_footer runs late in page rendering.
  3. Final Answer:

    init -> Option D
  4. Quick Check:

    add_rewrite_endpoint called on init hook = A [OK]
Hint: Use init hook for rewrite endpoints [OK]
Common Mistakes:
  • Using wp_enqueue_scripts instead of init
  • Adding endpoints in admin_menu hook
  • Placing code in wp_footer hook
3. Given this code snippet, what will be the effect on the URL structure?
add_action('init', function() {
  add_rewrite_endpoint('special', EP_PERMALINK | EP_PAGES);
});
medium
A. Adds '/special/' as an endpoint to permalinks and pages URLs
B. Removes all existing endpoints from URLs
C. Creates a new admin menu called 'special'
D. Flushes rewrite rules automatically

Solution

  1. Step 1: Analyze add_rewrite_endpoint parameters

    The first parameter 'special' is the endpoint name; the second parameter sets where it applies: permalinks and pages.
  2. Step 2: Understand the effect on URLs

    This adds '/special/' to URLs of posts and pages, allowing custom handling of that URL part.
  3. Final Answer:

    Adds '/special/' as an endpoint to permalinks and pages URLs -> Option A
  4. Quick Check:

    Endpoint 'special' added to permalinks/pages = B [OK]
Hint: Endpoint name + location = new URL part [OK]
Common Mistakes:
  • Thinking it removes endpoints
  • Confusing endpoints with admin menus
  • Assuming rewrite rules flush automatically
4. What is missing or incorrect in this code that registers a custom endpoint?
add_action('init', function() {
  add_rewrite_endpoint('promo', EP_ROOT);
});
medium
A. The endpoint name 'promo' is invalid
B. Rewrite rules are not flushed after adding the endpoint
C. The hook 'init' is incorrect for this function
D. The constant EP_ROOT cannot be used with add_rewrite_endpoint

Solution

  1. Step 1: Check endpoint registration correctness

    The endpoint name 'promo' is valid, and EP_ROOT is a valid location constant.
  2. Step 2: Identify missing step

    After adding endpoints, rewrite rules must be flushed (usually once) to apply changes; this code does not flush rules.
  3. Final Answer:

    Rewrite rules are not flushed after adding the endpoint -> Option B
  4. Quick Check:

    Flush rewrite rules after adding endpoints = C [OK]
Hint: Flush rewrite rules after adding endpoints [OK]
Common Mistakes:
  • Skipping rewrite rules flush
  • Using wrong hook instead of init
  • Thinking endpoint names must be special
5. You want to add a custom endpoint 'download' that works on posts and pages, and you want to flush rewrite rules only once after activation. Which code snippet correctly achieves this?
hard
A.
function add_download_endpoint() {
  add_rewrite_endpoint('download', EP_PERMALINK | EP_PAGES);
}
add_action('init', 'add_download_endpoint');

register_activation_hook(__FILE__, function() {
  add_download_endpoint();
  flush_rewrite_rules();
});
B.
add_action('init', function() {
  add_rewrite_endpoint('download', EP_ALL);
  flush_rewrite_rules();
});
C.
function add_download_endpoint() {
  add_rewrite_endpoint('download', EP_ROOT);
  flush_rewrite_rules();
}
add_action('init', 'add_download_endpoint');
D.
register_activation_hook(__FILE__, function() {
  add_rewrite_endpoint('download', EP_PERMALINK | EP_PAGES);
});

Solution

  1. Step 1: Register endpoint on init hook

    Function add_download_endpoint adds the endpoint on 'init' hook, which is correct.
  2. Step 2: Flush rewrite rules only once on activation

    Using register_activation_hook to call the endpoint function and then flush rewrite rules ensures flushing happens once on plugin activation.
  3. Step 3: Evaluate other options

    add_action('init', function() {
      add_rewrite_endpoint('download', EP_ALL);
      flush_rewrite_rules();
    });
    flushes rules on every page load (bad).
    function add_download_endpoint() {
      add_rewrite_endpoint('download', EP_ROOT);
      flush_rewrite_rules();
    }
    add_action('init', 'add_download_endpoint');
    flushes inside init (bad).
    register_activation_hook(__FILE__, function() {
      add_rewrite_endpoint('download', EP_PERMALINK | EP_PAGES);
    });
    does not flush rules at all.
  4. Final Answer:

    Register endpoint on 'init' hook and flush rewrite rules once on plugin activation -> Option A
  5. Quick Check:

    Register on init + flush once on activation = A [OK]
Hint: Flush rewrite rules once on activation, not every load [OK]
Common Mistakes:
  • Flushing rewrite rules on every page load
  • Not flushing rewrite rules at all
  • Registering endpoint outside init hook
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