admin管理员组

文章数量:1122846

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( '', 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/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: '/',
            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.

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.

Share Improve this question edited Aug 21, 2018 at 3:25 saurav.rox asked Aug 20, 2018 at 10:45 saurav.roxsaurav.rox 2051 silver badge13 bronze badges 6
  • developer.wordpress.org/rest-api/using-the-rest-api/… – Jacob Peattie Commented Aug 20, 2018 at 10:56
  • Thanks for the reply @JacobPeattie. I have kept the url of the site( where I want to add post ) in the wp_remote_post function and the same url on my js like xhr.setRequestHeader( 'Authentication', 'Basic ' + btoa( 'saurab:saurav123' ) ); Am I doing wrong? – saurav.rox Commented Aug 20, 2018 at 11:04
  • Are you using the basic auth plugin? – Jacob Peattie Commented Aug 20, 2018 at 11:08
  • Yah I have just activated it. – saurav.rox Commented Aug 20, 2018 at 11:08
  • Hang on, where/why are you using wp_remote_post()? Are you making this request with JS or PHP? – Jacob Peattie Commented Aug 20, 2018 at 11:10
 |  Show 1 more comment

1 Answer 1

Reset to default 0

Your JS is sending the request directly, so abc_add_post() appears to be entirely unnecessary. The issue with your JavaScript is that this part it still within the string started with ":

xhr.setRequestHeader( 'Authentication', 'Basic ' + btoa( 'saurab:saurav123' ) );

To use a function and concatenate it you need to close the already open string:

xhr.setRequestHeader( 'Authentication', 'Basic '" + btoa( 'saurab:saurav123' ) + "');

本文标签: WordPress Rest API Create Post