WordPress文章插入函数:wp_insert_post


【描述】
该函数可在数据库中插入文章(及页面)。它可以进行处理变量,检查操作,填充日期/时间等缺失变量等工作。该函数以对象作为变量,返回已创建文章的编号(出错时返回0)。

【使用方法】

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

【参数】

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

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

  1. $post = array(
  2.  
  3. 'ID' => [ <post id> ] //需要更新的文章编号
  4.  
  5. 'menu_order' => [ <order> ] //如果新文章是页面,设置显示顺序
  6.  
  7. 'comment_status' => [ 'closed' | 'open' ] // 评论的状态,'closed'关闭评论.
  8.  
  9. 'ping_status' => [ 'closed' | 'open' ] // ping的状态,'closed' 关闭 pingbacks和trackbacks
  10.  
  11. 'pinged' => [ ? ] //该文章被ping到的地址
  12.  
  13. 'post_author' => [ <user ID> ] //作者编号
  14.  
  15. 'post_category' => [ array(<category id>, <...>) ] //文章归类数组
  16.  
  17. 'post_content' => [ <the text of the post> ] //文章内容,必填
  18.  
  19. 'post_date' => [ Y-m-d H:i:s ] //文章编辑日期
  20.  
  21. 'post_date_gmt' => [ Y-m-d H:i:s ] //文章编辑GMT日期
  22.  
  23. 'post_excerpt' => [ <an excerpt> ] //摘要信息
  24.  
  25. 'post_name' => [ <the name> ] // (slug) 文章别名
  26.  
  27. 'post_parent' => [ <post ID> ] //新文章的父文章编号
  28.  
  29. 'post_password' => [ ? ] //文章浏览密码
  30.  
  31. 'post_status' => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] //新文章的状态
  32.  
  33. 'post_title' => [ <the title> ] //文章标题,必填
  34.  
  35. 'post_type' => [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] //文章类型:文章、页面、链接、菜单、其他定制类型
  36.  
  37. 'tags_input' => [ '<tag>, <tag>, <...>' ] //标签字符串
  38.  
  39. 'to_ping' => [ ? ] //该文章需要ping到的地址
  40.  
  41. 'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // 附加注释数组
  42.  
  43. );

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

默认: false

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

【使用方法】

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

【例子】

// 创建一个文章对象

  1. $my_post = array(
  2.  
  3. 'post_title' => 'My post',
  4.  
  5. 'post_content' => 'This is my post.',
  6.  
  7. 'post_status' => 'publish',
  8.  
  9. 'post_author' => 1,
  10.  
  11. 'post_category' => array(8,39)
  12.  
  13. );
  14.  
  15.  
  16. //入库
  17.  
  18. wp_insert_post( $my_post );

【安全】

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

【源码位置】

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

  1. /**
  2. * Insert a post.
  3. *
  4. * If the $postarr parameter has 'ID' set to a value, then post will be updated.
  5. *
  6. * You can set the post date manually, but setting the values for 'post_date'
  7. * and 'post_date_gmt' keys. You can close the comments or open the comments by
  8. * setting the value for 'comment_status' key.
  9. *
  10. * The defaults for the parameter $postarr are:
  11. * 'post_status' – Default is 'draft'.
  12. * 'post_type' – Default is 'post'.
  13. * 'post_author' – Default is current user ID ($user_ID). The ID of the user who added the post.
  14. * 'ping_status' – Default is the value in 'default_ping_status' option.
  15. * Whether the attachment can accept pings.
  16. * 'post_parent' – Default is 0. Set this for the post it belongs to, if any.
  17. * 'menu_order' – Default is 0. The order it is displayed.
  18. * 'to_ping' – Whether to ping.
  19. * 'pinged' – Default is empty string.
  20. * 'post_password' – Default is empty string. The password to access the attachment.
  21. * 'guid' – Global Unique ID for referencing the attachment.
  22. * 'post_content_filtered' – Post content filtered.
  23. * 'post_excerpt' – Post excerpt.
  24. *
  25. * @since 1.0.0
  26. * @uses $wpdb
  27. * @uses $wp_rewrite
  28. * @uses $user_ID
  29. * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
  30. * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
  31. * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
  32. * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
  33. * @uses wp_transition_post_status()
  34. *
  35. * @param array $postarr Elements that make up post to insert.
  36. * @param bool $wp_error Optional. Allow return of WP_Error on failure.
  37. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
  38. */
  39. function wp_insert_post($postarr, $wp_error = false) {
  40. global $wpdb, $wp_rewrite, $user_ID;
  41.  
  42. $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
  43. 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
  44. 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
  45. 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0,
  46. 'post_content' => '', 'post_title' => '');
  47.  
  48. $postarr = wp_parse_args($postarr, $defaults);
  49.  
  50. unset( $postarr[ 'filter' ] );
  51.  
  52. $postarr = sanitize_post($postarr, 'db');
  53.  
  54. // export array as variables
  55. extract($postarr, EXTR_SKIP);
  56.  
  57. // Are we updating or creating?
  58. $update = false;
  59. if ( !empty($ID) ) {
  60. $update = true;
  61. $previous_status = get_post_field('post_status', $ID);
  62. } else {
  63. $previous_status = 'new';
  64. }
  65.  
  66. if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) && ('attachment' != $post_type) ) {
  67. if ( $wp_error )
  68. return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
  69. else
  70. return 0;
  71. }
  72.  
  73. if ( empty($post_type) )
  74. $post_type = 'post';
  75.  
  76. if ( empty($post_status) )
  77. $post_status = 'draft';
  78.  
  79. if ( !empty($post_category) )
  80. $post_category = array_filter($post_category); // Filter out empty terms
  81.  
  82. // Make sure we set a valid category.
  83. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
  84. // 'post' requires at least one category.
  85. if ( 'post' == $post_type && 'auto-draft' != $post_status )
  86. $post_category = array( get_option('default_category') );
  87. else
  88. $post_category = array();
  89. }
  90.  
  91. if ( empty($post_author) )
  92. $post_author = $user_ID;
  93.  
  94. $post_ID = 0;
  95.  
  96. // Get the post ID and GUID
  97. if ( $update ) {
  98. $post_ID = (int) $ID;
  99. $guid = get_post_field( 'guid', $post_ID );
  100. $post_before = get_post($post_ID);
  101. }
  102.  
  103. // Don't allow contributors to set the post slug for pending review posts
  104. if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
  105. $post_name = '';
  106.  
  107. // Create a valid post name. Drafts and pending posts are allowed to have an empty
  108. // post name.
  109. if ( empty($post_name) ) {
  110. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  111. $post_name = sanitize_title($post_title);
  112. else
  113. $post_name = '';
  114. } else {
  115. $post_name = sanitize_title($post_name);
  116. }
  117.  
  118. // 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
  119. if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
  120. $post_date = current_time('mysql');
  121.  
  122. if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
  123. if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) )
  124. $post_date_gmt = get_gmt_from_date($post_date);
  125. else
  126. $post_date_gmt = '0000-00-00 00:00:00';
  127. }
  128.  
  129. if ( $update || '0000-00-00 00:00:00' == $post_date ) {
  130. $post_modified = current_time( 'mysql' );
  131. $post_modified_gmt = current_time( 'mysql', 1 );
  132. } else {
  133. $post_modified = $post_date;
  134. $post_modified_gmt = $post_date_gmt;
  135. }
  136.  
  137. if ( 'publish' == $post_status ) {
  138. $now = gmdate('Y-m-d H:i:59');
  139. if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
  140. $post_status = 'future';
  141. } elseif( 'future' == $post_status ) {
  142. $now = gmdate('Y-m-d H:i:59');
  143. if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) )
  144. $post_status = 'publish';
  145. }
  146.  
  147. if ( empty($comment_status) ) {
  148. if ( $update )
  149. $comment_status = 'closed';
  150. else
  151. $comment_status = get_option('default_comment_status');
  152. }
  153. if ( empty($ping_status) )
  154. $ping_status = get_option('default_ping_status');
  155.  
  156. if ( isset($to_ping) )
  157. $to_ping = preg_replace('|\s+|', "\n", $to_ping);
  158. else
  159. $to_ping = '';
  160.  
  161. if ( ! isset($pinged) )
  162. $pinged = '';
  163.  
  164. if ( isset($post_parent) )
  165. $post_parent = (int) $post_parent;
  166. else
  167. $post_parent = 0;
  168.  
  169. // Check the post_parent to see if it will cause a hierarchy loop
  170. $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
  171.  
  172. if ( isset($menu_order) )
  173. $menu_order = (int) $menu_order;
  174. else
  175. $menu_order = 0;
  176.  
  177. if ( !isset($post_password) || 'private' == $post_status )
  178. $post_password = '';
  179.  
  180. $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
  181.  
  182. // expected_slashed (everything!)
  183. $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' ) );
  184. $data = apply_filters('wp_insert_post_data', $data, $postarr);
  185. $data = stripslashes_deep( $data );
  186. $where = array( 'ID' => $post_ID );
  187.  
  188. if ( $update ) {
  189. do_action( 'pre_post_update', $post_ID );
  190. if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  191. if ( $wp_error )
  192. return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
  193. else
  194. return 0;
  195. }
  196. } else {
  197. if ( isset($post_mime_type) )
  198. $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
  199. // If there is a suggested ID, use it if not already present
  200. if ( !empty($import_id) ) {
  201. $import_id = (int) $import_id;
  202. if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
  203. $data['ID'] = $import_id;
  204. }
  205. }
  206. if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
  207. if ( $wp_error )
  208. return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
  209. else
  210. return 0;
  211. }
  212. $post_ID = (int) $wpdb->insert_id;
  213.  
  214. // use the newly generated $post_ID
  215. $where = array( 'ID' => $post_ID );
  216. }
  217.  
  218. if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
  219. $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
  220. $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  221. }
  222.  
  223. if ( is_object_in_taxonomy($post_type, 'category') )
  224. wp_set_post_categories( $post_ID, $post_category );
  225.  
  226. if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') )
  227. wp_set_post_tags( $post_ID, $tags_input );
  228.  
  229. // new-style support for all custom taxonomies
  230. if ( !empty($tax_input) ) {
  231. foreach ( $tax_input as $taxonomy => $tags ) {
  232. $taxonomy_obj = get_taxonomy($taxonomy);
  233. if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical.
  234. $tags = array_filter($tags);
  235. if ( current_user_can($taxonomy_obj->cap->assign_terms) )
  236. wp_set_post_terms( $post_ID, $tags, $taxonomy );
  237. }
  238. }
  239.  
  240. $current_guid = get_post_field( 'guid', $post_ID );
  241.  
  242. if ( 'page' == $data['post_type'] )
  243. clean_page_cache($post_ID);
  244. else
  245. clean_post_cache($post_ID);
  246.  
  247. // Set GUID
  248. if ( !$update && '' == $current_guid )
  249. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  250.  
  251. $post = get_post($post_ID);
  252.  
  253. if ( !empty($page_template) && 'page' == $data['post_type'] ) {
  254. $post->page_template = $page_template;
  255. $page_templates = get_page_templates();
  256. if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
  257. if ( $wp_error )
  258. return new WP_Error('invalid_page_template', __('The page template is invalid.'));
  259. else
  260. return 0;
  261. }
  262. update_post_meta($post_ID, '_wp_page_template', $page_template);
  263. }
  264.  
  265. wp_transition_post_status($data['post_status'], $previous_status, $post);
  266.  
  267. if ( $update ) {
  268. do_action('edit_post', $post_ID, $post);
  269. $post_after = get_post($post_ID);
  270. do_action( 'post_updated', $post_ID, $post_after, $post_before);
  271. }
  272.  
  273. do_action('save_post', $post_ID, $post);
  274. do_action('wp_insert_post', $post_ID, $post);
  275.  
  276. return $post_ID;
  277. }