Here is an example of PHP code that can be used to submit a post to a WordPress site using the WordPress REST API:
<?php // Replace these values with your own $site_url = 'http://example.com'; $api_key = 'your-api-key'; // Set up the API request $url = $site_url . '/wp-json/wp/v2/posts'; $headers = array( 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ); // Set up the post data $data = array( 'title' => 'My New Post', 'content' => 'This is the content of my new post', 'status' => 'publish' ); // Send the POST request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Print the response print_r($response);
This code sends a POST request to the /wp-json/wp/v2/posts
endpoint of the WordPress site, passing the post data in the request body as JSON. The Authorization
header is used to pass the API key, which is required to authenticate the request.
The post data in this example includes the title, content, and status of the post. You can add other fields as needed, such as the excerpt
, categories
, or tags
. You can also use the draft
status if you want to save the post as a draft instead of publishing it immediately.
Note that this code assumes that the WordPress REST API is already enabled on the site and that you have an API key with the necessary permissions to create posts. You can learn more about the WordPress REST API and how to use it in the WordPress REST API Handbook.