How To Programmatically Create a WordPress Post

How can I programmatically create a WordPress post from my plugin. which WordPress native function should I use

You can use WordPress native function wp_insert_post to create a WordPress post programmatically. Here is the example to show you how to create a WordPress post programmatically.

$author_id = 1; // the id of author 
$title = 'My First Post'; // title of your first post
$post_id = null;

if( null == get_page_by_title( $title ) ) {
    $slug  = sanitize_title($title);
    $post_id = wp_insert_post( array(
    'comment_status' => 'closed',
    'ping_status' => 'closed',
    'post_author' => $author_id,
    'post_name' => $slug,
    'post_title' => $title,
    'post_status' => 'publish',
    'post_type' => 'post'));
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments