You can insert WordPress posts programatically. Create a post without ever opening the Gutenberg editor – and here’s how.
Use wp_insert_post() To Insert Posts Programatically
You can pass your post data to wp_insert_post in array format. The array has keys equal to the column name in the database. So, for example, ‘post_title’ for the post title, ‘post_content’ for the content, etc. See your database wp_posts table structure for key names or check out the documentation for wp_insert_post().
Example Of Insert Post Programatically
Please note that you should not fire this on every page load. You want this to fire after you perform an action, such as posting a form or reading data from a database.
For example purposes, I just wrapped it in a conditional of if (isset($_GET[‘insert’]). That way it doesn’t fire unless I add ?insert onto the URL of my page.
/**
* Scottsweb.dev - create wordpress post programatically
* https://scottsweb.dev/how-to-insert-wordpress-posts-programatically/
*/
// this should not fire all the time,
// you should perform an action here.
//
// i'm just using if (isset($_GET['insert'])) for this example
if (isset($_GET['insert'])) {
$post_data = array(
'post_title' => 'Test Insert Post',
'post_status' => 'publish',
'post_content' => 'Test post content',
'post_category' => array(78)
);
$post_id = wp_insert_post($post_data);
if ($post_id) {
// continue
} else {
// error_log, display error message, etc
}
}
Adding Categories & Taxonomies
You can also add categories and taxonomies to your posts directly in the wp_insert_post() call. Just pass an array of post categories to post_category key in your array. Or tax_input for tags. You can also use meta_input to specify meta data in the corresponding wp_postmeta table. Pretty cool!
In the example I put post_category of 78. This is just for the example I did. If you don’t remove it, it may cause an error if category id of 78 is not present.
Check The Value Returned By wp_insert_post()
By checking wp_insert_post() return value, you can identify if the post was inserted or if there was an error. I’ve included boilerplate conditional in my coding where you could perform actions based on success or failure of wp_insert_post()
See more WordPress How-To’s.