REST API – Create, Update or Delete posts using Basic Auth and HTTP API (ok)
https://rudrastyh.com/wordpress/rest-api-create-delete-posts.html
Last updated
https://rudrastyh.com/wordpress/rest-api-create-delete-posts.html
Last updated
Updated on Mar 22nd, 2019 in
First of all, basic authentication won’t work until you install a special plugin, what plugin – depends on a way you choose. I will show you two of them.
This method isn’t recommended in WordPress Codex, because in each API call you have to send actual usernames and passwords, but you can use this method for test purposes.
To begin using it, you have to download a special plugin from github (I use the link from the official WordPress documentation page).
There is no way to perform Basic Auth in WordPress Rest API without this plugin installed. Once the plugin is activated on your website (I mean the website you want to interact with API), we can try examples below.
Ok, this method is much better. You have to install Application Passwords plugin, it is available from WordPress plugins repository, so you can find it in your website admin area on the Plugins > Add New page.
Once you installed this plugin, make sure, that your REST API is not turned off, then go to the very bottom of a user profile page and generate an app password there.
No needs to use user’s actual passwords anymore.
Where to insert all the code from this post? I hope you know this but just in case.
First of all I want to remind you that we have 2 websites.
The first website – is the website where the post should be created, the first website also should have any of the mentioned above plugins installed.
The second website – is the website that will interact with the first one. It will have all the code.
You can see wp_remote_post()
function in the code – it is a WordPress function, so you have to insert in somewhere inside WP environment. For my test purposes I just created a randomly named PHP file just in WordPress root directory and added at the beginning of the file require('wp-load.php');
. When I try to access this file in browser, it does the work.
LOGIN:PASSWORD
on line 3 is the pair of username and password of a website user (the first website, and if you’ve installed Application Passwords, you have to use the generated token instead), that have the capabilities to create, update and delete posts.
Let’s just update the title of the created post. Replace {POST_ID} with the ID of the post you would like to update. If you still not sure where to get it, read this tutorial.
If you add ?force=true
at the end of the request URI, the post will be removed permanently without moving to trash.
This was small introduction into Basic Authentication in WordPress REST API.