Is it possible to login to my different WP website from another WP website (they have different domain and host) ?
Actually, I am trying to create a post on one of my site from my another site using Rest API?
I don't even know if it is possible?
If it is possible, can anyone please shade some light on this?
I have been trying hard but I am stuck from past few days. All I am getting is 401() error on return.
I can share my codes for further explanation.
class MyPlugin
{
function __construct()
{
add_action( 'wp_ajax_abc_add_post', array( $this, 'abc_add_post' ) );
add_action( 'wp_ajax_nopriv_abc_add_post', array( $this, 'abc_add_post' ) );
add_action( 'wp_footer', array( $this, 'my_js' ) );
}
function abc_add_post()
{
$api_response = wp_remote_post( 'https://test.com/wp-json/wp/v2/posts', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'saurab:saurav123' )
),
'body' => array(
'title' => 'My test',
'status' => 'draft', // ok, we do not want to publish it immediately
'content' => 'lalala',
'categories' => 1, // category ID
'tags' => '1', // string, comma separated
'date' => '2018-08-17T10:00:00', // YYYY-MM-DDTHH:MM:SS
'excerpt' => 'Read this awesome post',
'password' => '',
'slug' => 'new-test-post' // part of the URL usually
// more body params are here:
// developer.wordpress.org/rest-api/reference/posts/#create-a-post
)
) );
$body = json_decode( $api_response['body'] );
// you can always print_r to look what is inside
print_r($api_response);
if( wp_remote_retrieve_response_message( $api_response ) === 'Created' ) {
echo 'The post ' . $body->title->rendered . ' has been created successfully';
}
else{
echo "here";
}
die();
}
function my_js()
{
echo "<script>
jQuery( document ).ready( function ( $ ) {
$( '#my-submit' ).on( 'click', function(e) {
e.preventDefault();
var title = 'test'
var content = 'this is test';
var status = 'draft';
var data = {
title: title,
content: content
};
$.ajax({
method: 'POST',
'Accept': 'application/json',
'Content-Type': 'application/json',
url: 'https://saurabadhikari.com.np/wp-json/wp/v2/posts/',
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', WTEAjaxData.nonce );
xhr.setRequestHeader( 'Authentication', 'Basic ' + btoa( 'saurab:saurav123' ) );
},
success : function( response ) {
alert('yes');
console.log( response );
},
fail : function( response ) {
alert('no');
console.log( response );
}
});
});
} );
</script>";
}
}
new MyPlugin;
Thank you.
wp_remote_post
function and the same url on my js likexhr.setRequestHeader( 'Authentication', 'Basic ' + btoa( 'saurab:saurav123' ) );
Am I doing wrong?wp_remote_post()
? Are you making this request with JS or PHP?