1

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.

6
  • 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? 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? Commented Aug 20, 2018 at 11:10

1 Answer 1

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' ) + "');
5
  • I have corrected my codes. Now I am getting this error on console: Request header field Authentication is not allowed by Access-Control-Allow-Headers in preflight response.
    – saurav.rox
    Commented Aug 21, 2018 at 7:02
  • This indicates that the server you are sending the request to, saurabadhikari.com.np, is configured to not accept the Authentication header. The correct header is Authorization, regardless. Commented Aug 21, 2018 at 7:08
  • Server side function function wp_rest_allow_all_cors() { remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' ); // Add a Custom filter. add_filter( 'rest_pre_serve_request', function( $value ) { header( 'Access-Control-Allow-Origin: *' ); header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' ); header( 'Access-Control-Allow-Credentials: true' ); header( 'Access-Control-Allow-Authorization: true' ); header( 'Access-Control-Allow-X-WP-Nonce: true' ); return $value; }); } / Why nonce is not supported? X-WP-Nonce is not allowed :(
    – saurav.rox
    Commented Aug 21, 2018 at 7:18
  • 1
    Previous Authntication error is fixed now. Thanks to you. Now nonce error is seen on console as I explained above :( Request header field X-WP-Nonce is not allowed by Access-Control-Allow-Headers in preflight response.
    – saurav.rox
    Commented Aug 21, 2018 at 7:20
  • I was able to figure out myself. Thank you for your time. Thank you again.
    – saurav.rox
    Commented Aug 21, 2018 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.