How to Use the wp_insert_post Function in WordPress to Insert Custom Posts

How to Use the wp_insert_post Function in WordPress to Insert Custom Posts

The WordPress wp_insert_post function allows you to insert custom posts into your website’s database using code. With this powerful tool, you can effortlessly create and manage dynamic content, surpassing the limitations of the standard post-creation process.

If you need to automate content generation, manage custom post types, or assign metadata and taxonomies via code, then wp_insert_post is the solution you’ve been searching for.

This article will uncover the benefits of using the wp_insert_post function and explore its parameters. We’ll also guide you through practical examples, illustrating how to use this function to create, customize, and manage various post types.

Download all in one WordPress cheat sheet

Why Use the wp_insert_post Function

Creating and managing posts manually can be time-consuming, especially with a large content volume. It’s particularly evident when exporting your WordPress posts to a new website.

Fortunately, with the wp_insert_post function, you can streamline your post-creation workflow and efficiently automate content generation. Not only does this save time, but it also minimizes the risk of human errors during data entry, ensuring your content is consistently accurate.

Additionally, WordPress supports various post types for different purposes, such as blog posts, pages, products, or custom post types. The versatility of wp_insert_post lets you tailor your content structure to suit your website’s unique requirements.

Parameters for wp_insert_post

Like other WordPress functions such as get_posts, the wp_insert_post function also has various parameters to facilitate custom post insertion. Here are some of the key parameters that you should be familiar with:

  • ID – The ID of the post to update. If provided, the function will attempt to edit the post with the given ID. Default is 0 (no update).
  • post_author – The ID of the post author. Default is the current user ID.
  • post_content – The content of the post. Default is an empty string.
  • post_content_filtered – The filtered post content. Default is an empty string.
  • post_title – The title of the post. Default is an empty string.
  • post_status – The status of the post (e.g., publish, draft, private). Default post status is publish.
  • post_type – The post type (e.g., post, page, custom post type). Default is post.
  • post_date – The date of the post. Default is the current date and time.
  • post_excerpt – The excerpt of the post. Default post excerpt is an empty string.
  • post_name – The post’s slug (URL-friendly version of the title). Default is the sanitized post title.
  • post_parent – The ID of the parent post (if the post is a child of another post). Default post parent is 0 (no parent).
  • post_password – The password to protect the post (if password-protected). Default is an empty string.
  • post_category – An array of category IDs to assign to the post. Default is an empty array.
  • tags_input – An array of tags to assign to the post. Default is an empty array.
  • tax_input – An array of taxonomies and terms to assign to the post. Default is an empty array.
  • meta_input – An array of post meta values keyed by the post meta key. Default is an empty array.

The basic syntax of the wp_insert_post function is as follows:

$post_id = wp_insert_post( $args, $wp_error );

$args is an array containing the post data and its corresponding parameters, while $wp_error is set to true to return a WP_Error object on failure. When executed, the function returns the ID of the newly inserted post on success or an error handling object otherwise.

Suggested Reading

For a complete list of all available wp_insert_post parameters, you can refer to the official WordPress documentation page.

How to use the wp_insert_post Function in WordPress

The wp-includes/post.php file is located in the File Manager

In this section, we’ll see practical examples of using the wp_insert_post function to insert custom posts. You can add your custom code to the wp-includes/post.php file to use this function. On Hostinger’s WordPress plans, the file can be accessed via the File Manager.

We’ll explore three common scenarios to showcase this function’s versatility and potential:

How to Insert a Post and Check for Errors

Let’s start with a basic example of inserting a new post using the wp_insert_post function. The code below demonstrates how to validate the post data, handle errors, and provide feedback to users in case of any issues during the insertion process.

// Include the necessary WordPress files
require_once(ABSPATH . 'wp-admin/includes/post.php');

// Create an array of post data for the new post
$new_post = array(
    'post_title'   => 'Sample Post Title', // Valid post name
    'post_content' => 'This is a custom post with error handling.', // Unslashed post data - Set the content of the new post
    'post_status'  => 'publish', // Unslashed post data - Set the status of the new post to 'publish'
    'post_author'  => 1, // Replace with the desired author's user ID
    'post_date'    => '2024-07-25 12:00:00', // Unslashed post data - Set a custom post date and time
);

// Insert post into the database
$post_id = wp_insert_post($new_post, true); // Use $wp_error set to true for error handling

// Check if there was an error during post insertion
if (is_wp_error($post_id)) {
    // Error occurred while inserting the post
    echo "Error: " . $post_id->get_error_message();
} else {
    // The post was successfully inserted, and $post_id contains the post ID
    echo "Post inserted successfully. New Post ID: " . $post_id;
}

If you want to update an existing post, you can utilize the code below:

// Include the necessary WordPress files
require_once(ABSPATH . 'wp-admin/includes/post.php');

$updated_post = array(
    'ID'           => $post_id, // Existing post ID
    'post_content' => 'This is the updated content of the post.', // Updated post content
);

// Update post in the database
$updated_post_id = wp_update_post($updated_post); // Updated post ID

// Check for errors during post updating
if (is_wp_error($updated_post_id)) { // Check if the result is a WP_Error object
    $error_message = $updated_post_id->get_error_message(); // Retrieve the error message
    // Handle the error, e.g., display an error message to the user
    echo "Error while updating the post: " . $error_message;
} else {
    // The post was successfully updated
    echo "Post updated successfully. New Post ID: " . $updated_post_id;
}

How to Insert a New Post Into a WordPress Database

Let’s delve deeper into using the wp_insert_post function to insert new post data and explore additional parameters to set custom post fields such as the post author, post date, and post category.

// Include the necessary WordPress files
require_once(ABSPATH . 'wp-includes/post.php');

// Create an array of post details for the new post
$new_post = array(
    'post_title'    => 'Test Post with Metadata', // Parsed post data - Set the title of the new post
    'post_content'  => 'This is a custom post with metadata and taxonomy terms.', // Post content - Set the content of the new post
    'post_type'     => 'post', // Processed post data - Set the post type to 'post'
    'post_status'   => 'publish', // Post status - Set the status of the new post to 'publish'
    'post_author'   => 1, // Replace with the desired author's user ID
    'post_date'     => '2024-07-21 12:00:00', // Post date - Set a custom post date and time
    'tags_input'    => array('tag1', 'tag2', 'tag3'), // Processed attachment post data - Set tags for the new post
    'page_template' => 'custom-template.php', // Invalid page template - Set a custom page template for the post
);

// Insert WordPress post into the database
$post_id = wp_insert_post($new_post); // Existing attachment post - Set the existing post ID for updating

// Check if the post was successfully inserted
if (!is_wp_error($post_id)) {
    // The post was successfully inserted, and $post_id contains the post ID

// Get the post meta field based on the post ID
    $meta_value = get_post_meta($post_id, 'meta_key_name', true);

    // Add custom post categories (replace with actual category IDs)
    $post_categories = array(2, 4); // Filters attachment post data - Category IDs to assign to the post
    wp_set_post_categories($post_id, $post_categories); // Set post categories

    // Add custom post meta data
    update_post_meta($post_id, '_custom_meta_key', 'Custom Meta Value'); // Replace '_custom_meta_key' with your custom meta key and set its value

    echo "Post inserted successfully. New Post ID: " . $post_id;
} else {
    // Error occurred while inserting the post
    echo "Error: " . $post_id->get_error_message();
}

How to Insert a Post With Custom Taxonomy and Post Meta Data

This example includes inserting a post with custom taxonomy terms and additional post metadata. WordPress taxonomy allows you to organize and categorize posts more flexibly.

// Include the necessary WordPress files
require_once(ABSPATH . 'wp-includes/post.php');

// Create an array of post data for the new post
$new_post = array(
    'post_title'    => 'Custom Post with Taxonomy and Meta Data', // Otherwise unmodified post data - Set the title of the new post
    'post_content'  => 'This is a custom post with taxonomy and meta data.', // Post content - Set the content of the new post
    'post_type'     => 'post', // Post type - Set the post type to 'post'
    'post_status'   => 'pending', // Pending review posts - Set the status of the new post to 'pending' for review
    'post_author'   => 1, // Replace with the desired author's user ID
    'post_date'     => '2024-08-05 12:00:00', // Post date - Set a custom post date and time
    'post_name'     => 'custom-post-taxonomy-meta', // Otherwise unmodified post data - Set the post slug
);

// Insert post into the database
$post_id = wp_insert_post($new_post);

// Check if the post was successfully inserted
if (!is_wp_error($post_id)) {
    // The post was successfully inserted, and $post_id contains the post ID

    // Add custom post categories (replace with actual category IDs)
    $post_categories = array(2, 4); // Category IDs to assign to the post
    wp_set_post_categories($post_id, $post_categories); // Set post categories

    // Add post meta data
    update_post_meta($post_id, '_custom_meta_key', 'Custom Meta Value'); // Sanitized attachment post data - Replace '_custom_meta_key' with your custom meta key and set its value

    // Add custom taxonomy terms (replace with actual taxonomy and term IDs)
    wp_set_object_terms($post_id, array(3, 5), 'custom_taxonomy'); // Set custom taxonomy terms

    echo "Post inserted successfully with custom taxonomy and meta data. New Post ID: " . $post_id;
} else {
    // Error occurred while inserting the post
    echo "Error: " . $post_id->get_error_message();
}

Conclusion

The wp_insert_post function empowers WordPress websites with seamless custom post insertion, streamlining the process of adding or updating content. WordPress site owners and developers ensure consistency and accuracy throughout their websites by utilizing this function.

Whether you’re a seasoned WordPress developer looking to optimize your workflows or a beginner eager to expand your knowledge, understanding wp_insert_post is a valuable skill that will significantly benefit your WordPress website.

Moreover, you can leverage wp_insert_post with other WordPress features, such as the WordPress Loop, to dynamically power content display. This synergy allows you to provide exceptional experiences for your website’s visitors.

Author
The author

Ariffud Muhammad

Ariffud is a Technical Content Writer with an educational background in Informatics. He has extensive expertise in Linux and VPS, authoring over 200 articles on server management and web development. Follow him on LinkedIn.