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

bb-theme-wordpress

BB Theme WordPress: A Comprehensive Review and Guide

Welcome to the world of BB Theme WordPress Are you searching for the perfect WordPress theme to bring your website to life? Look no further! BB WordPress Theme is here to help you design a […]

How-To-Delete-A-WordPress

How to Delete a Theme in WordPress: A Step-by-Step Guide

Easy Ways to Delete Any Theme in WordPress Do you want to remove a WordPress theme and are looking for guidance on how to do it? Removing a theme can help declutter your site and […]

Salient-WP

Salient WordPress Theme: A Comprehensive Guide for Beginners

If you’re looking for a WordPress theme that combines versatility, functionality, and style, the salient wordpress theme is worth considering. salient wordpress theme is a multi-purpose WordPress theme that caters to various niches, including business, […]