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

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 […]

Hide product category or product on shop page

Hide product category or product on shop page

Hello Guys today we gonna learn how can we hide specific product category, specific product on shop page. We are going to do this with the help of code snippets. You can directly add these […]

add-conversion-tracking-code-in-thank-you-page-woocommerce

Add conversion tracking code in thank you page Woocommerce

Hi Guys Today we are going to learn how to add conversion tracking code in order thank you page. We will do this using custom snippet in function.php