How to Insert Post Programmatically in WordPress (PHP Code Snippets)

To insert a post programmatically in WordPress, pass an array of post fields to wp_insert_post(). It returns the new post ID, or 0 on failure. To change a post that already exists, use wp_update_post() instead, because wp_insert_post() with an ID resets every field you leave out.

We ran every snippet in this guide on WordPress 7.1.4 (PHP 8.3) in a throwaway WordPress Playground site, including the edge cases, so the results quoted below are what WordPress actually did. The full parameter list is in the official wp_insert_post() reference.

Key Takeaways
  • wp_insert_post() returns the new post ID, 0 on failure, or a WP_Error if you pass true as the second argument.
  • Valid statuses are publish, draft, pending, private and future. WordPress saves whatever you pass, so a typo like public creates a post with an unregistered status.
  • Updating with wp_insert_post() and only an ID and title wiped the post’s content and set it back to draft. wp_update_post() kept both.
  • Code that runs without a logged-in user (cron jobs, WP-CLI scripts) saves posts with author 0, strips iframes and scripts, and silently ignores tax_input.
  • Wrap your data in wp_slash(), or WordPress strips backslashes: C:\Users\andy was saved as C:Usersandy.

Insert a post with wp_insert_post()

Build an array of fields and pass it in. Anything you leave out gets a default, including post_status, which defaults to draft.

<?php
$post_id = wp_insert_post(
    array(
        'post_title'   => 'My new post',
        'post_content' => 'Content to insert.',
        'post_status'  => 'publish',
        'post_author'  => 1,
    ),
    true // Return a WP_Error on failure instead of 0.
);

if ( is_wp_error( $post_id ) ) {
    error_log( $post_id->get_error_message() );
} else {
    echo 'Inserted post ' . $post_id;
}

With true as the second argument, a failure comes back as a WP_Error with a reason. For example, a post with no title, content or excerpt returned “Content, title, and excerpt are empty.” Without it, you only get 0.

Run this inside a function you call once, such as an admin action, a WP-CLI command or a cron job, not on every page load, or you will create a new post each time it runs.

The fields you will use most

FieldWhat it does
post_title, post_content, post_excerptThe post’s text. Content can include block markup.
post_statuspublish, draft, pending, private or future. Defaults to draft.
post_typepost by default. Use page or any registered custom post type.
post_authorUser ID of the author. Defaults to the current user, which is 0 when nobody is logged in.
post_datePublish date. A future date with publish status schedules the post.
post_nameThe slug. Generated from the title if you leave it out.
post_categoryArray of category IDs.
meta_inputArray of custom field keys and values, saved with the post. Find posts by these values later with meta_query.
tax_inputTerms for other taxonomies, but only saved if the current user can assign them.
The full list is in the official wp_insert_post() reference.

Insert a custom post type with custom fields

Set post_type to your custom post type and pass custom fields in meta_input, which saves them in the same call:

<?php
$post_id = wp_insert_post(
    array(
        'post_title'   => 'My new portfolio item',
        'post_content' => 'Project details.',
        'post_status'  => 'publish',
        'post_type'    => 'portfolio',
        'meta_input'   => array(
            'client_name' => 'Acme Inc.',
            'source_url'  => 'https://example.com',
        ),
    )
);

You can read those values back with get_post_meta(). The older approach of calling update_post_meta() after inserting still works, since wp_insert_post() returns the new ID.


Add categories and tags

post_category takes an array of category IDs and worked even with no user logged in. tax_input is different: WordPress only saves those terms if the current user can assign them. In our logged-out test, tax_input with two tags saved none, and no error was returned. Setting the tags afterward with wp_set_object_terms() worked:

<?php
$post_id = wp_insert_post(
    array(
        'post_title'    => 'My new post',
        'post_content'  => 'Content to insert.',
        'post_status'   => 'publish',
        'post_category' => array( 12 ),
    )
);

if ( $post_id ) {
    wp_set_object_terms( $post_id, array( 'alpha', 'beta' ), 'post_tag' );
}

Update an existing post with wp_update_post()

Passing an ID to wp_insert_post() updates that post, but every field you leave out falls back to its default. In our test, updating only the title this way wiped the content and changed the status from published to draft. wp_update_post() loads the existing post first and merges your changes, so the same update kept the content and status:

<?php
$result = wp_update_post(
    array(
        'ID'         => 15,
        'post_title' => 'My new post title',
    ),
    true
);

if ( is_wp_error( $result ) ) {
    error_log( $result->get_error_message() );
}

Gotchas when no user is logged in

Cron jobs, WP-CLI scripts and other code that runs outside a logged-in session have no current user, and that changes how wp_insert_post() behaves. Here is what our logged-out test showed:

  • The post’s author was set to 0. Pass post_author explicitly.
  • Content was filtered: an iframe was removed, and a <script> tag was stripped down to its text. The same content inserted as an administrator kept the iframe, because administrators have the unfiltered_html capability.
  • tax_input terms were ignored, as covered above.

If your importer needs to keep embeds, run it as a specific trusted user with wp_set_current_user() before inserting, and only for content you trust:

<?php
wp_set_current_user( 1 ); // An administrator's user ID.

$post_id = wp_insert_post( $postarr );

Backslashes are the other common surprise. wp_insert_post() expects slashed data, so it strips one level of backslashes. Content of C:\Users\andy was saved as C:Usersandy until we wrapped the array in wp_slash():

<?php
$post_id = wp_insert_post(
    wp_slash(
        array(
            'post_title'   => 'Paths',
            'post_content' => 'C:\\Users\\andy',
            'post_status'  => 'draft',
        )
    )
);

Avoid inserting duplicate posts

If your code imports from a feed or API, store each item’s source ID in a custom field and check for it before inserting:

<?php
$existing = new WP_Query(
    array(
        'post_type'      => 'post',
        'post_status'    => 'any',
        'meta_key'       => 'source_id',
        'meta_value'     => $item_id,
        'fields'         => 'ids',
        'posts_per_page' => 1,
        'no_found_rows'  => true,
    )
);

if ( ! $existing->posts ) {
    wp_insert_post(
        array(
            'post_title'   => $item_title,
            'post_content' => $item_content,
            'post_status'  => 'publish',
            'meta_input'   => array( 'source_id' => $item_id ),
        )
    );
}

WordPress also has post_exists(), which matches by title, but it lives in wp-admin/includes/post.php and isn’t loaded on the front end or in cron.


Other ways to create posts with code

If you are not writing PHP inside WordPress, there are two other routes:

Frequently asked questions

Where is the official wp_insert_post() documentation?

It is on the WordPress developer reference at developer.wordpress.org/reference/functions/wp_insert_post/, which lists every field the function accepts, its return values and its source code.

What does wp_insert_post() return?

The new post’s ID on success. On failure it returns 0, or a WP_Error object if you pass true as the second argument. For example, a post with no title, content or excerpt fails with “Content, title, and excerpt are empty.”

Why was my post saved as a draft?

post_status defaults to draft when you leave it out. Updating an existing post with wp_insert_post() also resets the status, so in our test a published post went back to draft. Pass post_status, and use wp_update_post() for updates.

How do I set a featured image on a post I inserted?

Upload or find the image’s attachment ID, then call set_post_thumbnail( $post_id, $attachment_id ) after wp_insert_post() returns the new post ID.

Can I schedule a post with wp_insert_post()?

Yes. Set post_status to publish and post_date to a future date in your site’s timezone, and WordPress saves the post as future, which publishes it at that time.

Picture of Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 15 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way. Found this article helpful? Buy Me A Coffee

3 Responses

  1. Excellent article, but how do I include in the import attachments of the post from the external php website and the associated photos?

  2. I can create posts using the same method as mentioned but I face problem in pagination of these posts. It creates posts and also links for the pagination, but displays 404 on any of the links except 1st.

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Tips Monthly
Get the latest from SmartWP to your inbox.