Create a Post with WordPress REST API | Example & Full Code

WordPress, being a powerful and versatile content management system, provides developers and users with the ability to interact with its core functionalities through REST API. In this how to guide, you will learn how to programmatically create a post with WordPress REST API.

How to Create a Post with WordPress REST API

Requirements

  • WordPress Application Password
  • Knowledge of PHP & HTML

I assume, you already know about WordPress Application Password and have already generated one. If not, then you can check my step-by-step instructions on generating a WordPress Application Password here.

WordPress API Endpoint to Create New Posts

WordPress REST API Endpoint for creating new posts is https://YOUR_WEBSITE_URL/wp-json/wp/v2/posts

An API endpoint is a URL where an application, WordPress, in our case, receives requests to perform specific actions assigned to that endpoint in application’s backend. Similarly, the above WordPress API endpoint handles new posts requests.

Code to Create a New Post Programmatically in WordPress

I am using PHP cURL programming language to make a REST API call to create a new post in WordPress website. If you are not familiar with this language, then you can convert this into any other language like JavaScript, Python or any other language of your choice with the help of ChatGPT, Claude.ai or any other chatbot service.

Following, you will find the complete working code to create a new post in your WordPress website using WordPress REST API.

<?php

    // Post Title
    $post_title = "Post Created with WordPress REST API";

    // Post Content
    $post_body = "<p>Hello user, this the body content of the post created using WordPress REST API code provided by oyehoyeai.com</p>";

    // WordPress REST API Url to Create a New Post
    $wp_post_url = "https://YOUR_WORDPRESS_WEBSITE_URL.com/wp-json/wp/v2/posts";


    // WordPress User ID 
    $user_id = "REPLACE_WITH_WORDPRESS_USER_ID";
    
    // WordPress User Password
    $user_password = "REPLACE_WITH_WORDPRESS_USER_PASSWORD";
    
    // WordPress Application Password
    $user_app_password = "REPLACE_WITH_WORDPRESS_APPLICATION_PASSWORD";

    $credentials = $user_id . ':' . $user_app_password;
    $token = base64_encode($credentials);
    $header = array('Authorization: Basic ' . $token);

    
    $post_status = "draft";
    
    $post_data = array(
        "title" => $post_title,
        "content" => $post_body,
        "status" => $post_status
    );


    $wp_post_url = $wp_post_url . '?' . http_build_query($post_data);

    $ch = curl_init($wp_post_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    }

    curl_close($ch);

    // Printing the API Call result data in array format
    echo "<pre>";
    print_r(json_decode($response, true));
    echo "</pre>";
?>

Create New Post WordPress API Code Explained

This PHP code is a script that uses the WordPress REST API to create a new post on a WordPress website. Let’s break down the main components of the code:

Post Information:

  • $post_title: Specifies the title for the new post.
  • $post_body: Defines the content or body of the post.
  • $wp_post_url: Represents the WordPress REST API endpoint for creating a new post.

User Authentication:

  • $user_id: Should be replaced with the WordPress user ID.
  • $user_password: Should be replaced with the password of the WordPress user.
  • $user_app_password: Should be replaced with the application password generated in WordPress for secure API authentication.

Authentication Header:

  • $credentials: Combines the user ID and application password for basic authentication.
  • $token: Encodes the credentials in base64 format for use in the Authorization header.
  • $header: Contains the Authorization header with the encoded token.

Post Data:

  • $post_status: Specifies the status of the new post (in this case, “draft”).
  • $post_data: An array containing the title, content, and status of the new post.

Building API URL:

  • The script appends the post data to the WordPress REST API URL using http_build_query().

cURL Setup:

  • Initializes a cURL session with the WordPress REST API endpoint.
  • Sets cURL options, including POST request, post data, headers, and returning the transfer as a string.

API Call:

  • $response = curl_exec($ch); Executes the cURL session to make the API call, creating a new post on the WordPress site and puts the response, success or error, returned by WordPress REST API into a php variable “$response“.

Response Handling:

  • Checks for cURL errors and prints an error message if any.
  • curl_close($ch); Closes the cURL session.

Prints API Call Result:

  • Prints the result of the API call in an array format by decoding the JSON response.

This script essentially serves as a client to interact with the WordPress REST API, utilizing basic authentication with an application password for security. It constructs the necessary data, makes an API call to create a new post, and then prints the result.

Data Returned by WordPress REST API Create Post Endpoint, If Success

If your code runs successfully, then you should receive a similar response data, containing post id, date, slug, tpe, link, etc. to the one shown below (pleas note, this is not complete response data, it is just the top of response returned by wordpress rest api)

<!-- if your code runs successfully then you should receive a similar response to this one (this is not complete response data, it is just the top of response returned by wordpress rest api-->
Array
(
    [id] => 28776
    [date] => 2024-01-15T03:13:42
    [date_gmt] => 2024-01-15T03:13:42
    [guid] => Array
        (
            [rendered] => https://oyehoyeai.com/?p=28776
            [raw] => https://oyehoyeai.com/?p=28776
        )

    [modified] => 2024-01-15T03:13:42
    [modified_gmt] => 2024-01-15T03:13:42
    [password] => 
    [slug] => 
    [status] => draft
    [type] => post
    [link] => https://oyehoyeai.com/?p=28776
    [title] => Array
        (
            [raw] => Post Created with WordPress REST API
            [rendered] => Post Created with WordPress REST API
        )

    [content] => Array
        (
            [raw] => Hello user, this the body content of the post created using WordPress REST API code provided by oyehoyeai.com
            [rendered] => 
Hello user, this the body content of the post created using WordPress REST API code provided by oyehoyeai.com

Conclusion

Today, you’ve acquired the knowledge of utilizing the WordPress REST API to programmatically create a new post in WordPress from any remote location. If you have any questions or face any difficulties in implementing the code, then do not hesitate to comment me, I read each and every comment.

Leave a Comment