The function clears the passed data; makes some checks; fills in the missing variables (for example, if you do not pass the date of the post, the date will be set automatically).
For update existing post data, you need to set $postarr['ID'] parameter, which must contain the ID of the post you need to update. Or use special function wp_update_post() which works based on this function.
This function requires slashed data. This means that if you pass NOT $_POST data, then you need to process the passing data array with wp_slash().
IMPORTANT: specify 'post_author' => user_id if the code is called not by a user, e.g., via CRON, REST, etc. By default, the ID of the current user is inserted there, and if there is no current user, we get post_author = 0 and a lot of bugs.
Keep in mind that the function has hooks, for example, save_post, wp_insert_post. In the functions of such hooks, you can use $_POST or $_GET data. These data may be missing in the front end. Therefore, when the function is used in the front, it can cause errors. In such cases, look for errors in the functions of such hooks.
Categories need to be passed as an array of integers that match the category IDs in the database. This is the case even where only one category is assigned to the post.
This function processes the passing data with sanitize_post(), which checks and clears the values of all fields (kses, etc.). Therefore, there is no need to worry about clearing the data being transferred.
However, you may need to remove HTML, JavaScript, or PHP tags from the title of the post or other fields. WordPress does not do this automatically. This can be easily done by using wp_strip_all_tags(), especially when users of yor site can publish posts from the front end:
// insert post to DB
$post_id = wp_insert_post( array(
'post_title' => wp_strip_all_tags( $_POST['post_title'] ), // clear all tags
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 20,59 )
) );
Emoji note
From version 4.2, with the introduction of Emoji. This function automatically converts smiley symbols in the fields 'post_title', 'post_content', 'post_excerpt', if the encoding of DB tables utf8, not utf8mb4. This is doing with help of wp_encode_emoji() function.
An array of data to be inserted into the Database. The array keys are exactly equal to the fields of the wp_posts table, the passed keys values will be inserted into the value of the table fields.
If you pass the ID parameter, the existing post with the same ID will be edited, i.e. when you specify the ID parameter, you update the post, not create a new one.
Parameters of the transmitted array:
$data = array(
'ID' => <post id>, // Do you update an existing post?
'menu_order' => <order>, // If the post is a "static page", set its order in the menu.
'comment_status' => 'closed' | 'open', // 'closed' means that comments are closed.
'ping_status' => 'closed' | 'open', // 'closed' means the pings and notifications are off.
'pinged' => '', // separated list of URLs that have been pinged
'to_ping' => '', // Separated list of URLs that have been pinged
'post_author' => <user ID>, // ID of post author
'post_content' => <the text of the post>, // post content
'post_date' => Y-m-d H:i:s, // The time the post was created.
'post_date_gmt' => Y-m-d H:i:s, // The time the post was created in GMT time zone.
'post_excerpt' => <an excerpt>, // excerpt text
'post_name' => <the name>, // The alternate name of the entry (slug) will be used in the Url.
'post_parent' => <post ID>, // ID of the parent record, if necessary.
'post_password' => ?, // The password to view the post.
'post_status' => 'draft' | 'publish' | 'pending'| 'future' | 'private', // The status of the post being created.
'post_title' => <the title>,
'post_type' => 'post' | 'page' | 'nav_menu_item' | custom type,
'post_category' => array(<category id>, <...>), // Category to which the post belongs to.
'tags_input' => '<tag>, <tag>, <...>', // Post tags (indicated by names, slugs or ID).
'tax_input' => array( 'taxonomy_name' => array('term', 'term2') ), // Which taxonomies to attach the post to. Like 'post_category', but for new taxonomies.
'meta_input' => array( 'meta_key'=>'meta_value' ), // Add the specified meta fields. Default is ''. Since WP 4.4.
);
$ID(int)
The post ID. If equal to something other than 0, the post with that ID will be updated.
$post_author(int)
The ID of the user who added the post. Default is the current user ID.
$post_date(string)
The date of the post. Default is the current time.
$post_date_gmt(string)
The date of the post in the GMT timezone. Default is the value of $post_date.
$post_content(mixed)
The post content. Default empty.
$post_content_filtered(string)
The filtered post content. Default empty.
$post_title(string)
The post title. Default empty.
$post_excerpt(string)
The post excerpt. Default empty.
$post_status(string)
The post status. Default 'draft'.
$post_type(string)
The post type. Default 'post'.
$comment_status(string)
Whether the post can accept comments. Accepts 'open' or 'closed'. Default is the value of 'default_comment_status' option.
$ping_status(string)
Whether the post can accept pings. Accepts 'open' or 'closed'. Default is the value of 'default_ping_status' option.
$post_password(string)
The password to access the post. Default empty.
$post_name(string)
The post name. Default is the sanitized post title when creating a new post.
$to_ping(string)
Space or new line - separated list of URLs to ping. Default empty.
$pinged(string)
Space or new line - separated list of URLs that have been pinged. Default empty.
$post_modified(string)
The date when the post was last modified. Default is the current time.
$post_modified_gmt(string)
The date when the post was last modified in the GMT timezone. Default is the current time.
$post_parent(int)
Set this for the post it belongs to, if any.
$menu_order(int)
The order the post should be displayed in.
$post_mime_type(string)
The mime type of the post. Default empty.
$guid(string)
Global Unique ID for referencing the post. Default empty.
$post_category(array)
Array of category names, slugs, or IDs. Defaults to value of the 'default_category' option.
$tags_input(array)
Array of tag names, slugs, or IDs. Default empty.
$tax_input(array)
Array of taxonomy terms keyed by their taxonomy name. Default empty.
$meta_input(array)
Array of post meta values keyed by their post meta key. Default empty.
Notes
post_title and post_content are required
post_status: If post_status=future, you must specify the post_date in order for WordPress to know when to publish post.
tax_input: Equivalent to calling wp_set_post_terms() for each custom taxonomy in the array. if the current user does not have the capability to work with taxonomies then the definition of the tax_input parameter to attach the post to term will not work. To do this anyway, use wp_set_object_terms().
page_template: the page_template table field has been removed, now the template for the static page is set in wp_postmeta table. For doing this wp_insert_post() uses update_post_meta( $post_ID, '_wp_page_template', $page_template );
$wp_error(true/false)
Whether to return a WP_Error on failure. Default: false
Examples
Before using wp_insert_post(), you need to create a data array, which is then passed to the functions. In the array, at least you need to specify post_title and post_content otherwise the post will not be created. Other fields for which no data is specified will be created automatically, with default values.
You can specify more data in the array than it is shown below. The array keys are names of the WordPress Database wp_posts table fields.
$post_id = wp_insert_post( $POST['post_data'], true );
if( is_wp_error($post_id) ){
echo $post_id->get_error_message();
}
else {
// you can now use $post_id to add, for example
// meta field using add_post_meta() or update_post_meta()
}
0
#2 A simple example of inserting a new post into a WordPress Database
// Create an array
$post_data = array(
'post_title' => 'Заголовок записи',
'post_content' => 'Здесь должен быть контент (текст) записи.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
// Insert data into database
$post_id = wp_insert_post( wp_slash($post_data) );
Categories must be passed in the array, even if one category is specified. For example: 'post_category' => array(8)
See also: wp_set_post_terms() when you want to set custom taxonomies for a post.
0
#3 Insert post with custom taxonomy and post meta data