描述
wp_insert_post()函数可在数据库中插入文章(及页面)。

它可以进行处理变量,检查操作,填充日期/时间等缺失变量等工作。该函数以对象作为变量,返回已创建文章的编号(出错时返回0)。

 

使用方法

<?php wp_insert_post( $post, $wp_error ); ?>

 

函数参数

$post       (array) (必需) 一个文章对象. 与数据库wp_posts表中的字段一一对应

默认: 无
重要: 如果设置$post[‘ID’]的值,将不会创建 这个ID的文章. 设置这个值将会更新这个ID的文章. 简单的说,创建一个文章 $post[‘ID’] 必须为空或不设置这个值.

$post = array(
	'ID' => [  ] 						// 需要更新的文章编号
	'menu_order' => [  ] 				// 如果新文章是页面,设置显示顺序
	'comment_status' => [ 'closed' | 'open' ] 	// 评论的状态,'closed'关闭评论.
	'ping_status' => [ 'closed' | 'open' ] 		// ping的状态,'closed' 关闭 pingbacks和trackbacks
	'pinged' => [ ? ] 							// 该文章被ping到的地址
	'post_author' => [  ] 				// 作者编号
	'post_category' => [ array(, < ...>) ] 	// 文章归类数组
	'post_content' => [  ] 		// 文章内容,必填
	'post_date' => [ Y-m-d H:i:s ] 				// 文章编辑日期
	'post_date_gmt' => [ Y-m-d H:i:s ] 			// 文章编辑GMT日期
	'post_excerpt' => [  ] 			// 摘要信息
	'post_name' => [  ] 				// (slug) 文章别名
	'post_parent' => [  ] 				// 新文章的父文章编号
	'post_password' => [ ? ] 					// 文章浏览密码
	'post_status' => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] 			// 新文章的状态
	'post_title' => [  ] 			// 文章标题,必填
	'post_type' => [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] 	// 文章类型:文章、页面、链接、菜单、其他定制类型
	'tags_input' => [ ', , < ...>' ] 	// 标签字符串
	'to_ping' => [ ? ] 							// 该文章需要ping到的地址
	'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] 	// 附加注释数组
);

$wp_error    (布尔型) (可选) 失败时是否返回WP_Error对象

默认: false

 

返回的值

若文章成功加入数据库,返回文章编号。否则返回0.

 

例子

$my_post = array(
	'post_title' => 'My post',
	'post_content' => 'This is my post.',
	'post_status' => 'publish',
	'post_author' => 1,
	'post_category' => array(8,39)
);


//入库
wp_insert_post( $my_post );

 

【安全】

函数会自动过滤和检查文章信息的合法性,不需要用户自己来额外处理

【源码位置】

wp_insert_post() 位于 wp-includes/post.php

/**
 * Insert a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, but setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * The defaults for the parameter $postarr are:
 *     'post_status'   – Default is 'draft'.
 *     'post_type'     – Default is 'post'.
 *     'post_author'   – Default is current user ID ($user_ID). The ID of the user who added the post.
 *     'ping_status'   – Default is the value in 'default_ping_status' option.
 *                       Whether the attachment can accept pings.
 *     'post_parent'   – Default is 0. Set this for the post it belongs to, if any.
 *     'menu_order'    – Default is 0. The order it is displayed.
 *     'to_ping'       – Whether to ping.
 *     'pinged'        – Default is empty string.
 *     'post_password' – Default is empty string. The password to access the attachment.
 *     'guid'          – Global Unique ID for referencing the attachment.
 *     'post_content_filtered' – Post content filtered.
 *     'post_excerpt'  – Post excerpt.
 *
 * @since 1.0.0
 * @uses $wpdb
 * @uses $wp_rewrite
 * @uses $user_ID
 * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
 * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
 * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
 * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
 * @uses wp_transition_post_status()
 *
 * @param array $postarr Elements that make up post to insert.
 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
 */
function wp_insert_post($postarr, $wp_error = false) {
	 global $wpdb, $wp_rewrite, $user_ID;

	 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
	  'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
	  'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
	  'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
	  'post_content' => '', 'post_title' => '');

	 $postarr = wp_parse_args($postarr, $defaults);

	 unset( $postarr[ 'filter' ] );

	 $postarr = sanitize_post($postarr, 'db');

	 // export array as variables
	 extract($postarr, EXTR_SKIP);

	 // Are we updating or creating?
	 $update = false;
	 if ( !empty($ID) ) {
	  $update = true;
	  $previous_status = get_post_field('post_status', $ID);
	 } else {
	  $previous_status = 'new';
	 }

	 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
	  if ( $wp_error )
	   return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
	  else
	   return 0;
	 }

	 if ( empty($post_type) )
	  $post_type = 'post';

	 if ( empty($post_status) )
	  $post_status = 'draft';

	 if ( !empty($post_category) )
	  $post_category = array_filter($post_category); // Filter out empty terms

	 // Make sure we set a valid category.
	 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
	  // 'post' requires at least one category.
	  if ( 'post' == $post_type && 'auto-draft' != $post_status )
	   $post_category = array( get_option('default_category') );
	  else
	   $post_category = array();
	 }

	 if ( empty($post_author) )
	  $post_author = $user_ID;

	 $post_ID = 0;

	 // Get the post ID and GUID
	 if ( $update ) {
	  $post_ID = (int) $ID;
	  $guid = get_post_field( 'guid', $post_ID );
	  $post_before = get_post($post_ID);
	 }

	 // Don't allow contributors to set the post slug for pending review posts
	 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
	  $post_name = '';

	 // Create a valid post name.  Drafts and pending posts are allowed to have an empty
	 // post name.
	 if ( empty($post_name) ) {
	  if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
	   $post_name = sanitize_title($post_title);
	  else
	   $post_name = '';
	 } else {
	  $post_name = sanitize_title($post_name);
	 }

	 // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
	 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
	  $post_date = current_time('mysql');

	 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
	  if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
	   $post_date_gmt = get_gmt_from_date($post_date);
	  else
	   $post_date_gmt = '0000-00-00 00:00:00';
	 }

	 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
	  $post_modified     = current_time( 'mysql' );
	  $post_modified_gmt = current_time( 'mysql', 1 );
	 } else {
	  $post_modified     = $post_date;
	  $post_modified_gmt = $post_date_gmt;
	 }

	 if ( 'publish' == $post_status ) {
	  $now = gmdate('Y-m-d H:i:59');
	  if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
	   $post_status = 'future';
	 } elseif( 'future' == $post_status ) {
	  $now = gmdate('Y-m-d H:i:59');
	  if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
	   $post_status = 'publish';
	 }

	 if ( empty($comment_status) ) {
	  if ( $update )
	   $comment_status = 'closed';
	  else
	   $comment_status = get_option('default_comment_status');
	 }
	 if ( empty($ping_status) )
	  $ping_status = get_option('default_ping_status');

	 if ( isset($to_ping) )
	  $to_ping = preg_replace('|\s+|', "\n", $to_ping);
	 else
	  $to_ping = '';

	 if ( ! isset($pinged) )
	  $pinged = '';

	 if ( isset($post_parent) )
	  $post_parent = (int) $post_parent;
	 else
	  $post_parent = 0;

	 // Check the post_parent to see if it will cause a hierarchy loop
	 $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );

	 if ( isset($menu_order) )
	  $menu_order = (int) $menu_order;
	 else
	  $menu_order = 0;

	 if ( !isset($post_password) || 'private' == $post_status )
	  $post_password = '';

	 $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);

	 // expected_slashed (everything!)
	 $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
	 $data = apply_filters('wp_insert_post_data', $data, $postarr);
	 $data = stripslashes_deep( $data );
	 $where = array( 'ID' => $post_ID );

	 if ( $update ) {
	  do_action( 'pre_post_update', $post_ID );
	  if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
	   if ( $wp_error )
		return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
	   else
		return 0;
	  }
	 } else {
	  if ( isset($post_mime_type) )
	   $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
	  // If there is a suggested ID, use it if not already present
	  if ( !empty($import_id) ) {
	   $import_id = (int) $import_id;
	   if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
		$data['ID'] = $import_id;
	   }
	  }
	  if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
	   if ( $wp_error )
		return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
	   else
		return 0;
	  }
	  $post_ID = (int) $wpdb->insert_id;

	  // use the newly generated $post_ID
	  $where = array( 'ID' => $post_ID );
	 }

	 if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
	  $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
	  $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
	 }

	 if ( is_object_in_taxonomy($post_type, 'category') )
	  wp_set_post_categories( $post_ID, $post_category );

	 if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
	  wp_set_post_tags( $post_ID, $tags_input );

	 // new-style support for all custom taxonomies
	 if ( !empty($tax_input) ) {
	  foreach ( $tax_input as $taxonomy => $tags ) {
	   $taxonomy_obj = get_taxonomy($taxonomy);
	   if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
		$tags = array_filter($tags);
	   if ( current_user_can($taxonomy_obj->cap->assign_terms) )
		wp_set_post_terms( $post_ID, $tags, $taxonomy );
	  }
	 }

	 $current_guid = get_post_field( 'guid', $post_ID );

	 if ( 'page' == $data['post_type'] )
	  clean_page_cache($post_ID);
	 else
	  clean_post_cache($post_ID);

	 // Set GUID
	 if ( !$update && '' == $current_guid )
	  $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );

	 $post = get_post($post_ID);

	 if ( !empty($page_template) && 'page' == $data['post_type'] ) {
	  $post->page_template = $page_template;
	  $page_templates = get_page_templates();
	  if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
	   if ( $wp_error )
		return new WP_Error('invalid_page_template', __('The page template is invalid.'));
	   else
		return 0;
	  }
	  update_post_meta($post_ID, '_wp_page_template',  $page_template);
	 }

	 wp_transition_post_status($data['post_status'], $previous_status, $post);

	 if ( $update ) {
	  do_action('edit_post', $post_ID, $post);
	  $post_after = get_post($post_ID);
	  do_action( 'post_updated', $post_ID, $post_after, $post_before);
	 }

	 do_action('save_post', $post_ID, $post);
	 do_action('wp_insert_post', $post_ID, $post);

	 return $post_ID;
}