庆云php

庆云php

WordPress插入文章到数据库,常用函数-wp_insert_post()

网络科技 0

2023年11月20日 每日一猜答案: 答案:ABC
每日一猜答案分析:

常用函数-wp_insert_post()

说明

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

用法

示例

调用wp_insert_post()前需创建对象以传递组成文章的必要元素。wp_insert_post()可自动填写默认表格,但用户需提供文章标题和内容,否则数据库写入不成功。 用户可在数据库中简单定义新关键字,之后就可以添加更多文章要素。关键字应与数据库wp_posts表格中纵列名称相匹配。
// Create post object    
  $my_post = array();    
  $my_post['post_title'] = 'My post';    
  $my_post['post_content'] = 'This is my post.';    
  $my_post['post_status'] = 'publish';    
  $my_post['post_author'] = 1;    
  $my_post['post_category'] = array(8,39);    

// Insert the post into the database    
  wp_insert_post( $my_post );  
上面提到的默认表格在函数主体中有所定义。定义如下:
$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' => ''  
);  

类别

需要将类别作为整数数组传递,该数组应与数据库中的类别编号相匹配。即使文章只属于某一项类别,情况也应如此。

参数

$post (对象)(必需)能表示可组成文章元素的对象。这些元素与数据库wp_posts表格中的纵列名称应一一对应。 默认值:空 文章数组的内容可取决于用户的默认值的信赖程度。下表列出了用户可为文章设置的所有选项:
$post = array(    
  'comment_status' => [ 'closed' | 'open' ] // 'closed' means no comments.    
  'ID' => [  ] //Are you updating an existing post?    
  'menu_order' => [  ] //If new post is a page, sets the order should it appear in the tabs.    
  'page_template => [