Today, we are going to learn How to Create WordPress Posts using Laravel. To create posts on a WordPress site using Laravel, you can use the WordPress XML-RPC API, which allows you to perform actions such as creating, editing, and deleting posts remotely. Here are the steps you can follow:
- Install the
php-xmlrpc
package using Composer by running the following command in your Laravel project directory:
composer require php-xmlrpc
- Create a new instance of the
IXR_Client
class, which represents the XML-RPC client, and connect it to the WordPress site:
$client = new \PhpXmlRpc\Client('http://your-wordpress-site.com/xmlrpc.php');
- Authenticate the client with the WordPress site by calling the
wp.getUsersBlogs
method, which returns information about the user’s blogs:
$username = 'your-wordpress-username';
$password = 'your-wordpress-password';
$request = new \PhpXmlRpc\Request('wp.getUsersBlogs', [
new \PhpXmlRpc\Value($username, 'string'),
new \PhpXmlRpc\Value($password, 'string'),
]);
$response = $client->send($request);
$blogId = $response->val[0]['blogid'];
- Create a new post by calling the
wp.newPost
method, which takes an array of post data as its parameter:
$title = 'Your post title';
$content = 'Your post content';
$categoryIds = [1, 2]; // IDs of the categories the post belongs to
$request = new \PhpXmlRpc\Request('wp.newPost', [
new \PhpXmlRpc\Value($blogId, 'int'),
new \PhpXmlRpc\Value($username, 'string'),
new \PhpXmlRpc\Value($password, 'string'),
new \PhpXmlRpc\Value([
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_category' => $categoryIds,
], 'struct'),
]);
$response = $client->send($request);
$postId = $response->val;
- Check if the post was created successfully by checking if
$postId
is not null.
That’s it! You should now be able to create posts on your WordPress site using Laravel. Note that there are many other methods available in the WordPress XML-RPC API, so you can also use them to perform other actions such as editing and deleting posts, managing categories and tags, and more.