How to Create WordPress REST API Using PHP
- Tech Area
- Last updated on: January 19, 2026
WordPress REST API allows developers to connect WordPress with mobile apps, React, Vue, or external PHP applications. It is one of the most trending WordPress development topics because modern websites rely heavily on APIs.
In this tutorial, you’ll learn how to create and use WordPress REST API using PHP, step by step, with real examples.
What Is WordPress REST API?
The WordPress REST API enables you to:
1. Access WordPress data in JSON format
2. Create custom endpoints
3. Perform CRUD operations (Create, Read, Update, Delete)
4. Connect WordPress with external apps
Example API URL:
https://example.com/wp-json/wp/v2/posts
Why WordPress REST API Is Trending
✔ Used in headless WordPress
✔ Required for React & mobile apps
✔ Faster than traditional PHP templates
✔ Essential for modern WordPress development
✔ Widely used in SaaS & dashboards
Create Custom REST API Endpoint in WordPress
Step 1: Add Code in functions.php
add_action('rest_api_init', function () {
register_rest_route('custom-api/v1', '/posts', array(
'methods' => 'GET',
'callback' => 'get_custom_posts_api',
));
});
Step 2: Create API Callback Function
function get_custom_posts_api() {
$args = array(
'post_type' => 'post',
'posts_per_page' => 5
);
$query = new WP_Query($args);
$posts = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = array(
'id' => get_the_ID(),
'title' => get_the_title(),
'link' => get_permalink(),
);
}
wp_reset_postdata();
}
return rest_ensure_response($posts);
}
Test Your REST API Endpoint
Open browser:
https://yourwebsite.com/wp-json/custom-api/v1/posts
Output (JSON):
[
{
"id": 12,
"title": "Sample Post",
"link": "https://yourwebsite.com/sample-post"
}
]
Create REST API Using PHP (POST Request)
register_rest_route('custom-api/v1', '/add-post', array(
'methods' => 'POST',
'callback' => 'create_post_api'
));
function create_post_api($request) {
$post_id = wp_insert_post(array(
'post_title' => sanitize_text_field($request['title']),
'post_content' => sanitize_textarea_field($request['content']),
'post_status' => 'publish'
));
return array(
'success' => true,
'post_id' => $post_id
);
}
Security Best Practices
✔ Use authentication (JWT / Application Passwords)
✔ Sanitize & validate input
✔ Restrict permissions using permission_callback
✔ Avoid exposing sensitive data
Where WordPress REST API Is Used
1. Headless WordPress websites
2. Mobile apps (Android / iOS)
3. React / Vue / Next.js apps
4. External PHP dashboards
5. Automation systems
Conclusion
Creating a WordPress REST API using PHP is an essential skill for modern developers. It allows you to build scalable, fast, and flexible applications while keeping WordPress as a powerful backend.
Join 20,000+ subscriber
