How to Create Posts in WordPress using REST_API?

Create Posts in WordPress using REST_API:

Creating posts in WordPress using the REST API involves making HTTP requests to the WordPress REST API endpoint for posts. Here is a basic guide on how you can do this:

Prerequisites:

    1. WordPress Site: Ensure that you have a WordPress site with the REST API enabled.
    2. Authentication: You might need to authenticate your requests. You can use basic authentication or OAuth depending on your requirements.

Steps to Create a Post:

1. Get Authorization Token (Optional):

  • If you are using authentication, obtain an authorization token. For basic authentication, you can use your WordPress username and password to get a token. For OAuth, you’ll need to follow the OAuth process to obtain a token.
  • 2. Construct API Request:

  • Use a tool like cURL or a programming language library (e.g., Python requests, JavaScript fetch) to make HTTP requests.
  • The endpoint for creating a post is usually wp-json/wp/v2/posts.
  • # Example cURL request for creating a post (replace the values accordingly)
    curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_TOKEN" -d '{
        "title": "Your Post Title",
        "content": "Your post content.",
        "status": "publish"
    }' https://your-wordpress-site.com/wp-json/wp/v2/posts
    

    3. Handle Response:

  • Check the response to ensure the post was created successfully. The new post ID might be included in the response.
  • Example response:

    {
      "id": 123,
      "title": {
        "rendered": "Your Post Title"
      },
      "content": {
        "rendered": "Your post content."
      },
      "status": "publish"
    }
    

    Leave a Reply

    Your email address will not be published. Required fields are marked *