The WordPress API is like a toolkit that developers use to build features inside WordPress, such as plugins or themes. It works within WordPress itself.
The WordPress REST API, however, is a way for external applications (like mobile apps or other websites) to interact with WordPress. It allows you to access WordPress data from outside, like getting posts or updating information, using simple web requests.
In short, the WordPress API is for internal development, while the WordPress REST API is for connecting WordPress to other apps or services from the outside.
Table of Contents
What is WordPress API?
The term “WordPress API” is a broad concept that encompasses all the application programming interfaces provided by WordPress. These APIs allow developers to interact with various parts of WordPress programmatically. Some examples of WordPress APIs include:
- Plugin API: Allows developers to create plugins and extend WordPress functionality.
- Theme API: Provides functions for theme development.
- Settings API: Enables the creation of administration pages and forms.
- Options API: Manages WordPress options (site settings).
- Metadata API: Handles metadata for posts, comments, and users.
- Shortcode API: Allows the creation of shortcodes for use in posts and pages.
- HTTP API: Simplifies the process of making HTTP requests.
These APIs are primarily used within the WordPress environment, often in plugin or theme development.
What is WordPress REST API?
The WordPress REST API, on the other hand, is a specific type of API that is part of the broader WordPress API ecosystem. It has some distinct characteristics:
- RESTful Architecture: It follows REST (Representational State Transfer) principles, which is a standard architectural style for web APIs.
- HTTP-based: It uses standard HTTP methods (GET, POST, PUT, DELETE) for different operations.
- JSON Data Format: It returns data in JSON format, which is widely supported and easy to work with in various programming languages.
- External Access: Unlike most other WordPress APIs, the REST API is designed to be accessed from outside the WordPress environment.
- Endpoints: It provides specific endpoints for different WordPress resources (posts, pages, users, etc.).
- Authentication: It supports various authentication methods for secure access.
- Core Integration: Since WordPress 4.7, the REST API has been integrated into WordPress core, making it a standard feature.
WordPress API vs WordPress REST API: Key Differences
- Scope:
- WordPress API is a broad term covering all APIs in WordPress.
- WordPress REST API is a specific API within the WordPress ecosystem.
- Usage:
- WordPress APIs are primarily used within WordPress (plugins, themes).
- The REST API is designed for both internal and external use.
- Data Format:
- Various WordPress APIs may use different data formats.
- The REST API consistently uses JSON.
- Access Method:
- Many WordPress APIs are accessed through PHP functions.
- The REST API is accessed via HTTP requests.
- Purpose:
- WordPress APIs serve various specific purposes (plugin development, theme customization, etc.).
- The REST API provides a standardized way to interact with WordPress data and functionality.
- External Integration:
- Traditional WordPress APIs are not easily accessible from external applications.
- The REST API is designed for easy integration with external applications, services, and frameworks.
Examples of WordPress API
Here are a few code examples showcasing how to use various WordPress APIs within the WordPress environment.
1. Plugin API (Creating a Simple Plugin)
The Plugin API allows developers to create custom plugins and extend WordPress.
<?php
/*
Plugin Name: Simple Greeting Plugin
Description: A simple plugin that adds a greeting message to the footer.
*/
function greeting_message() {
echo '<p style="text-align:center;">Hello, welcome to our website!</p>';
}
add_action('wp_footer', 'greeting_message');
?>
2. Theme API (Adding Custom Features to a Theme)
The Theme API helps developers add functionality to WordPress themes.
// Register a custom navigation menu
function register_custom_menu() {
register_nav_menu('custom-menu', __( 'Custom Menu', 'theme-slug' ));
}
add_action('init', 'register_custom_menu');
3. Settings API (Creating a Settings Page)
The Settings API allows you to create custom settings pages in the WordPress admin panel.
// Register a new settings section
function custom_settings_page() {
add_menu_page('Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page_content');
}
add_action('admin_menu', 'custom_settings_page');
// Create settings page content
function custom_settings_page_content() {
?>
<div class="wrap">
<h1>Custom Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('custom-settings-group');
do_settings_sections('custom-settings-group');
?>
<input type="text" name="custom_text" value="<?php echo esc_attr(get_option('custom_text')); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
// Register settings
function custom_register_settings() {
register_setting('custom-settings-group', 'custom_text');
}
add_action('admin_init', 'custom_register_settings');
4. Options API (Saving and Retrieving Options)
The Options API allows storing and retrieving options in the WordPress database.
// Save a custom option
update_option('custom_option', 'This is a custom option');
// Retrieve and display the custom option
$custom_option = get_option('custom_option');
echo 'Custom Option Value: ' . $custom_option;
5. Metadata API (Working with Post Metadata)
The Metadata API allows you to store custom metadata for posts, users, or comments.
// Add custom metadata to a post
add_post_meta($post_id, '_custom_meta_key', 'Custom Meta Value', true);
// Retrieve the custom metadata
$custom_meta_value = get_post_meta($post_id, '_custom_meta_key', true);
echo 'Post Meta Value: ' . $custom_meta_value;
6. Shortcode API (Creating Custom Shortcodes)
The Shortcode API lets you create custom shortcodes for posts and pages.
// Register a custom shortcode
function custom_greeting_shortcode() {
return '<p>Hello, this is a custom shortcode!</p>';
}
add_shortcode('custom_greeting', 'custom_greeting_shortcode');
// Use the shortcode in a post or page: [custom_greeting]
7. HTTP API (Making HTTP Requests)
The HTTP API simplifies making external HTTP requests from WordPress.
// Perform a GET request to an external API
$response = wp_remote_get('https://api.example.com/data');
// Check if the request was successful
if (is_wp_error($response)) {
echo 'Request failed.';
} else {
$body = wp_remote_retrieve_body($response);
echo 'API Response: ' . $body;
}
8. User API (Managing Users)
The User API allows you to manage WordPress users.
// Create a new user
$user_id = wp_create_user('new_username', 'password', 'email@example.com');
// Retrieve user info
$user_info = get_userdata($user_id);
echo 'User Email: ' . $user_info->user_email;
Each of these examples demonstrates how to use specific WordPress APIs to extend or interact with WordPress programmatically.
Examples of WordPress REST API
Here are several code examples that demonstrate how to use the WordPress REST API. These examples cover basic tasks such as retrieving posts, creating content, updating data, and deleting resources using HTTP requests.
1. Fetching Posts Using the REST API (GET Request)
This example shows how to fetch the latest posts from a WordPress site using the REST API.
GET https://example.com/wp-json/wp/v2/posts
Using cURL:
curl -X GET https://example.com/wp-json/wp/v2/posts
Example JavaScript (fetch):
fetch('https://example.com/wp-json/wp/v2/posts')
.then(response => response.json())
.then(posts => console.log(posts))
.catch(error => console.error('Error:', error));
This will return a list of the latest posts in JSON format, including titles, content, and other metadata.
2. Fetching a Single Post (GET Request)
To get a single post by its ID, use the following endpoint:
GET https://example.com/wp-json/wp/v2/posts/123
Using cURL:
curl -X GET https://example.com/wp-json/wp/v2/posts/123
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/posts/123')
.then(response => response.json())
.then(post => console.log(post))
.catch(error => console.error('Error:', error));
This fetches the post with the ID 123
.
3. Creating a New Post (POST Request)
To create a new post using the REST API, you need to authenticate (e.g., using Basic Authentication or OAuth). Here’s an example with Basic Authentication.
POST https://example.com/wp-json/wp/v2/posts
Using cURL:
curl -X POST https://example.com/wp-json/wp/v2/posts \
-H "Content-Type: application/json" \
-u username:password \
-d '{
"title": "New Post Title",
"content": "This is the content of the new post.",
"status": "publish"
}'
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('username:password')
},
body: JSON.stringify({
title: 'New Post Title',
content: 'This is the content of the new post.',
status: 'publish'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This will create and publish a new post with the specified title and content.
4. Updating an Existing Post (PUT Request)
To update an existing post, send a PUT
request with the post ID and the updated data.
PUT https://example.com/wp-json/wp/v2/posts/123
Using cURL:
curl -X PUT https://example.com/wp-json/wp/v2/posts/123 \
-H "Content-Type: application/json" \
-u username:password \
-d '{
"title": "Updated Post Title"
}'
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/posts/123', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('username:password')
},
body: JSON.stringify({
title: 'Updated Post Title'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This will update the title of the post with the ID 123
.
5. Deleting a Post (DELETE Request)
To delete a post, you can send a DELETE
request with the post ID.
DELETE https://example.com/wp-json/wp/v2/posts/123
Using cURL:
curl -X DELETE https://example.com/wp-json/wp/v2/posts/123 \
-H "Content-Type: application/json" \
-u username:password
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/posts/123', {
method: 'DELETE',
headers: {
'Authorization': 'Basic ' + btoa('username:password')
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This will delete the post with the ID 123
.
6. Fetching Categories (GET Request)
To fetch all categories, you can use the following endpoint:
GET https://example.com/wp-json/wp/v2/categories
Using cURL:
curl -X GET https://example.com/wp-json/wp/v2/categories
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/categories')
.then(response => response.json())
.then(categories => console.log(categories))
.catch(error => console.error('Error:', error));
This will return a list of all the categories available on the WordPress site.
7. Fetching Users (GET Request)
To get the list of users on the WordPress site, use the following endpoint:
GET https://example.com/wp-json/wp/v2/users
Using cURL:
curl -X GET https://example.com/wp-json/wp/v2/users
Example JavaScript:
fetch('https://example.com/wp-json/wp/v2/users')
.then(response => response.json())
.then(users => console.log(users))
.catch(error => console.error('Error:', error));
This returns the user data, such as username, email, and role.
These examples demonstrate how you can interact with the WordPress REST API to manage posts, categories, users, and other content programmatically using HTTP requests. The API allows easy access to data from outside WordPress, making it useful for applications, websites, and services that need to interact with a WordPress installation.
When to Use Which?
WordPress API Use:
Use traditional WordPress APIs when you’re developing within the WordPress environment (e.g., creating a plugin or theme).
WordPress REST API
Use the WordPress REST API when you need to:
- Access WordPress data from external applications
- Build decoupled or headless WordPress sites
- Create mobile apps that interact with WordPress
- Integrate WordPress with third-party services or applications
Final Thoughts
Understanding this distinction is crucial for WordPress developers. While the WordPress REST API has become increasingly important, especially for modern web development practices, the other WordPress APIs remain vital for traditional WordPress development and customization.