Custom REST API Endpoints

·

·

The WordPress REST API allows you to interact with WordPress data using standard HTTP requests, making it possible to build dynamic and modern front-end experiences. Beyond the built-in endpoints for posts, pages, and users, WordPress also lets you create custom REST API routes. Custom endpoints are especially useful when you want to expose specific data or run custom logic for applications, JavaScript widgets, or external systems.


✅ Example: Register a Custom REST Endpoint

Add this to your theme’s functions.php or a custom plugin:

add_action('rest_api_init', function(){
  register_rest_route('training/v1', '/message', [
    'methods'  => 'GET',
    'callback' => function(){
      return ['message' => 'Hello from custom API'];
    },
    'permission_callback' => '__return_true'
  ]);
});

🧠 How It Works

PartMeaning
rest_api_initAction hook that runs when WordPress registers REST routes
register_rest_route()Creates a custom API endpoint
training/v1Namespace and version for your API
/messageEndpoint path
methods => 'GET'HTTP method allowed (GET, POST, etc.)
callbackFunction that returns the response
permission_callbackControls who can access the endpoint

🌐 How to Access the Custom Endpoint

Visit this URL in your browser:

https://your-site.com/wp-json/training/v1/message

You’ll receive a JSON response:

{
  "message": "Hello from custom API"
}

📌 Key Takeaways

ConceptExplanation
Custom REST endpoints expand WordPress into an app platformUseful for headless sites or JavaScript front-ends
register_rest_route() defines the endpoint path and behaviorWorks inside rest_api_init hook
Endpoints return JSONEasy to use in mobile apps and SPA frameworks
permission_callback controls securityAlways validate access when needed

✅ What You Can Do Next

  • Return posts, metadata, or user details
  • Accept POST input and process forms via REST
  • Build React or Vue front-ends powered by WordPress
  • Create APIs for mobile apps or external clients