Insert post programmatically in WordPress
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',
);