Sometimes we need to create a WordPress post without login into a WordPress site; Here in this article, I am going to show how to create a WordPress post Programmatically by submitting the HTML Form with the help of a PHP script.
First, create your HTML form using any text editor.
<form name="myform" action="savepost.php" method="post">
<label for="post_title">post_title:</label><br>
<input type="text" id="post_title" name="post_title" value=""><br>
<label for="post_desc">post_desc:</label><br>
<textarea id="post_desc" name="post_desc"></textarea><br>
<br>
<input type="submit" value="Submit">
</form>
In this example, I am going to take only two fields only 1st post title and 2nd post description. When the user submits this form the savepost.php will create a new post on your WordPress website.
You have to define a few more parameters to save this form as a post, which includes post status, post date, post author, and post type.
post status
you can set post status as “draft” or “publish”.
post date:
Use date(‘Y-m-d H:i:s’) function to set post date time
post author
Check the wp_users table to get the user_id.
post type
You can set post type as “post” or “page.
This script must be saved on the WordPress site because the function wp_insert_post is defined in the wp_load.php file. And this file must be included in the script to use the wp_insert_post function else it will give an error that the function is not defined.
require_once './wp-load.php';
$post_title = isset($_POST['post_title']) ? $_POST['post_title'] : "";
$post_desc = isset($_POST['post_desc']) ? $_POST['post_desc'] : "";
$post_status = "draft";
$post_author = 1 ;// admin user_id is 1
$post_type="post";
$new_post = array(
'post_title' => "$post_title",
'post_content' => "$post_desc",
'post_status' => "$post_status",
'post_date' => date('Y-m-d H:i:s'),
'post_author' => "$post_author",
'post_type' => "$post_type"
);
$post_id = wp_insert_post($new_post);
//echo $post_id;
//var_dump($post_id); die;
if($post_id!=0)
{
echo "Post Created Successfully";
}
else{
echo "Unable to create post";
}