Insert post programmatically in WordPress

Insert post programmatically in WordPress

  • August 20, 2022

Today we are gonna learn how to insert post in database programmatically.

The function we are going to use is wp_insert_post()

For creating a post first you need to create a post array, below is the example of array to create a post.

$post = array(
    'post_title' => wp_strip_all_tags('Post Title'),
    'post_content' => 'Content of the post',
    'post_status' => 'publish',
);

After creating the array use the function to insert post in database.

$post_id = wp_insert_post($args);

This insert post function will return a post ID if post created successfully otherwise it will return. On failure It returns 0 or WP_error

For checking post created or not we use if condition

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

Here you can validate the post is created or not.

You can also use wp_insert_post() function to edit or update the post, for updating the post you just need to pass the post Id in the parameter array, like below

$post = array(
    'ID' => 35,
    'post_title' => wp_strip_all_tags('Post Title'),
    'post_content' => 'Content of the post',
    'post_status' => 'publish',
);

You can also insert custom post type using this function, you just need to pass the post type parameter for this eg: below

$post = array(
    'post_title' => wp_strip_all_tags('Post Title'),
    'post_content' => 'Content of the post',
    'post_status' => 'publish',
    'post_type' => 'movie',
);

Related Post

How to Create a Blog Website on WordPress

How to Create a Blog Website on WordPress

If you’re looking to start a blog website, WordPress is an excellent platform to use. It’s easy to use, customizable, and has a large community of users who can help you out if you run […]

Wordpress Offline Editor

Top 10 WordPress Offline Editor

If you’re a WordPress user, you know how important it is to have a reliable offline editor to help you manage your content. Whether you’re traveling, without an internet connection, or just prefer the convenience […]

Fix-Images-and-Broken-Links-by-Updating-Paths-in-WordPress

Fix Images and Broken Links by Updating Paths in WordPress

Today we will learn how to fix broken images link issue in WordPress, after migrating site from local server to live server or (one domain to another). This is a very common issue. The simple […]