How to insert post programmatically in WordPress

posted on by - 6116 views

WordPress gives us an awesome backend we can use, among other things, to publish or edit posts. Of course, it’s also possible to insert post programmatically by code, if for whatever reason we need to. That’s exactly what we’re going to learn in this tutorial.

Insert posts programmatically in WordPress

The function we’re going to use to do that is wp_insert_post().

So first of all, we’re going to create an array with all the parameters we need to insert the post.

$new = array(
    'post_title' => 'Our new post',
    'post_content' => 'This is the content of our new post.',
    'post_status' => 'publish'

This is the simplest way to create a new post, by defining its title, content and status. The array also accepts many other parameters, like ‘ID’, which will be used to edit an existing post; ‘post_author’, if you want the author to be different from the current user, and many others – check this page to know more about it.

Now that our array is created we can create the post:

$post_id = wp_insert_post( $new );

The function we just used will return the post ID on success, 0 or WP_Error on failure. So we can use the variable we just created, $post_id, to check if everything went well or to print an error. Something like the following:

if( $post_id ){
    echo "Post successfully published!";
} else {
    echo "Something went wrong, try again.";

As we said before, wp_insert_post() is also used to edit existing posts: to do that, the only thing we have to do is including the ID in our parameters array. Don’t know how to find an existing post ID? We talked about it some time ago, in this tutorial.

Of course, we can also use the function to insert pages or other post types: to do that, we just have to specify it into our array, with the parameter ‘post_type’ (default is post).