I'm using the current Apps script function to add a new post to my WordPress site:
var um_url = 'http://test.mywebsite.com/wp/wp-json/wp/v2/posts';
var um_headers = {
"Accept" : "application/json",
"Authorization": "Basic "+Utilities.base64Encode("user:passowrd"),
"Content-type":"application/json"
};
var um_options = {
"method":"POST",
"headers": um_headers,
"dataType" : 'json',
"data": {
title: "Foo title",
content: "Foo content",
status: "publish"
}
};
var um_response = UrlFetchApp.fetch(um_url, um_options);
var json = um_response.getContentText();
Logger.log(json);
}
But I'm getting this error:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}
I read other similar StackOverflow questions and they solved it by changing the .htacess file, unfortunately, this didn't solve my issue.
here is my .htaccess file
# BEGIN WP BASIC Auth
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</IfModule>
# END WP BASIC Auth
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
RewriteBase /
RewriteRule ^index\.php$ - [E=X-HTTP_AUTHORIZATION:% {HTTP:Authorization},QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wp/index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</IfModule>
# END WordPress
Can anyone help?
I just had almost exactly the same problem, trying to add something through REST API. The trick is that you need to send the REST WP Nonce (named wp_rest) through with the request, as either a header, or as part of the request variable...
if you use fetch, you can do this...
fetch( route, {
method: method,
headers: {
'X-WP-Nonce': wpApiSettings.nonce
}
} )
or add it to your query vars as '_wpnonce'
You can find the code that is setting the current user to 0 at wp-includes/rest-api.php on line 834 (ver 5.2.1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With