是否可以从另一个WP网站登录到我的不同WP网站(他们有不同的域和主机)?
实际上,我正在尝试使用Rest API从另一个站点在我的一个站点上创建帖子?
我甚至不知道这是否可能?
如果可能的话,谁能给这个遮光?
我一直在努力,但过去几天来我一直被困住。我得到的只是返回时的401()错误。
我可以分享我的代码以作进一步解释。
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;
谢谢你。