4

I'm trying to create a WordPress post using the REST API, OAuth, and cURL. However, I'm running into some trouble.

I'm able to create a blank post (no title, slug, etc) using the following code:

$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_POST => true,
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false);

This works as expected - authorizes successfully, and creates a blank post in WordPress. However, when I go to set the title (or any other property) by adding

CURLOPT_POSTFIELDS => "title=testTitle",

I get an error:

{
"data": {
    "code": "json_oauth1_signature_mismatch",
    "message": "OAuth signature does not match",
    "data": {
        "status": 401
    }
},
"headers": [],
"status": 401
}

What's interesting is that I'm able to set a title with success using Postman. Any ideas what I'm doing wrong? Any help would be greatly appreciated - been at this for hours.

1 Answer 1

0

"The REST API uses JSON exclusively as the request and response format, including error responses."

-- WordPress REST API Reference

I would try explicitly setting the content type/length and json encode your data with something like this (assuming you need to specify all the options you did in your code provided):

$data = array(
    'title' => 'testTitle',
    'content' => '',
);

$data = json_encode( $data );

$header = array(
    buildAuthorizationHeader( $oauth ),
    'Content-Type: application/json',
    'Content-Length: ' . strlen( $data ),
    'Expect:',
);

$options = array(
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_POST => true,
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_POSTFIELDS => $data,
);

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.