2

Actually I have no problems getting posts. I need to create posts with the REST API in php with file_get_contents.

This is my code:

json_decode(
    file_get_contents(
        "http://my-site.com/wp-json/wp/v2/posts",
        false,
        stream_context_create(
            array(
                "http" => array(
                    "header"  => "Content-type: text/json\r\n",
                    "method"  => "POST",
                    "content" => json_encode(
                        array(
                            "slug" => "article-2",
                            "title" => "Article 2",
                            "content" => "Created with rest api",
                        )
                    )
                ),
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false
                )
            )
        )
    ),
    true
);

And I get this error: failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

So I tried having an auth with real wp username and password:

"http" => array(
    "header"  => "Content-type: text/json\r\n"."Authorization: Basic " . base64_encode("$username:$password"),
    "method"  => "POST",
    "content" => json_encode(
        array(
            "slug" => "article-2",
            "title" => "Article 2",
            "content" => "Created with rest api",
        )
    )
)

But same result.

How can I insert a post with the REST API from php using file_get_contents?

3
  • 2
    Have you tried this code? v2.wp-api.org/guide/authentication/… Commented Aug 29, 2017 at 14:32
  • @AntonLukin yes, same problem Commented Aug 29, 2017 at 15:05
  • You'll need to install a plugin to add authentication, by default it requires a cookie and a nonce token, but for this you'll want a basic auth plugin or OAuth Commented Aug 29, 2017 at 15:22

1 Answer 1

2

You'll need to install a plugin to add authentication, by default it requires a cookie and a nonce token, but for CLI apps or PHP requests, you'll want to install a basic auth plugin or use OAuth1/2

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.