WordPress插入文章wp_insert_post详解-包含自定义分类和字段
我们知道wp_insert_post函数可在数据库中插入文章(及页面),它可以进行处理变量,检查操作,填充日期/时间等缺失变量等工作。可在数据库中插入文章(及页面)。它可以进行处理变量,检查操作,填充日期/时间等缺失变量等工作。该函数以对象作为变量,返回已创建文章的编号(出错时返回0)。一般情况下使用wp_insert_post函数向wordpress数据库插入文章或页面的情况比较少,这个WP函数在采集方面用得比较多。因此,如果你想做个采集软件,或者想写个wordpress采集接口,这个函数是必须会的,一起来学习下wp_insert_post函数的用法吧。
使用方法
官方描述,插入或更新一个文章或页面,传入id为更新,不传则创建。
<?php wp_insert_post( $post, $wp_error ); ?>
参数详解
(array) (必须) 包含更新或插入内容的数组,(int|WP_Error)成功返回post_id,失败返回0或wp_error。
- ‘ID’
(int) 文章ID,如果不等于0则更新,等于0则创建,默认为0。 - ‘post_author’
(int) 添加文章的作者,默认为当前用户。 - ‘post_date’
(string) 文章添加日期,默认为当前日期 - ‘post_date_gmt’
(string) 在格林尼治时间区域中的时间,默认为$post_date
的值. - ‘post_content’
(mixed) 文章内容,默认为空. - ‘post_content_filtered’
(string) 过滤后的帖子内容。默认空. - ‘post_title’
(string) 文章标题。默认空. - ‘post_excerpt’
(string) 文章摘要。默认空. - ‘post_status’
(string) 文章状态,默认为 ‘draft’. - ‘post_type’
(string) 文章类型,默认为 ‘post’. - ‘comment_status’
(string) 文章评论状态开关,默认是 ‘default_comment_status’ 配置项的值. - ‘ping_status’
(string) ping状态开关,默认是’default_ping_status’ 配置项的值. - ‘post_password’
(string) 文章阅读密码,默认为空. - ‘post_name’
(string) 文章的名字。默认情况下,在创建新文章时,必须使用经过净化的文章标题. - ‘to_ping’
(string) 空格或回车将url的列表分隔成ping,默认是空的. - ‘pinged’
(string) 空格或回车分隔的url列表,默认是空的. - ‘post_modified’
(string) 上次修改后的日期,默认是当前时间. - ‘post_modified_gmt’
(string) 最后在GMT时区修改后的日期,默认是当前时间. - ‘post_parent’
(int) 文章的父级文章ID,默认为 0. - ‘menu_order’
(int) 如果新文章为一个页面,可以设置一个页面序号,默认为 0. - ‘post_mime_type’
(string) 文章的mime类型,默认是空的. - ‘guid’
(string) 全局唯一ID,用于引用post,默认是空的. - ‘post_category’
(array) 文章分类目录,默认值为『default_category』选项的值. - ‘tags_input’
(array) 文章标签,默认为空. - ‘tax_input’
(array) 文章的自定义分类法项目,默认为空. - ‘meta_input’
(array) 自定义字段,默认为空. - page_template
页面模板文件的名称,如,template.php,默认为空。
简单案例:
//准备文章内容
$my_post = array(
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_content' => $_POST['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 8,39 )
);
// 插入文章到数据库
wp_insert_post( $my_post );
函数会自动过滤和检查文章信息的合法性,不需要用户自己来额外处理。
扩展详细:
今天在给某个客户开发一项功能的时候,遇到一个问题就是前台投稿页面如果插入自定义分类法呢,虽然wp_insert_post的传值参数里有一个tax_input用于插入自定义分类法的,但是好像并不好使。经过一番搜索,终于找到了解决方法:
在执行完wp_insert_post之后会返回一个$post_id,我们可以用下面这个函数插入自定义分类法的值:
wp_set_object_terms( $post_id, 'maker', 'domain' );//domain是自定义分类法,maker是slug值
$hierarchical_tax = array( 13, 10 ); // Array of tax ids.
$non_hierarchical_terms = 'tax name 1, tax name 2'; // Can use array of ids or string of tax names separated by commas
$post_arr = array(
'post_title' => 'Test post',
'post_content' => 'Test post content',
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'tax_input' => array(
'hierarchical_tax' => $hierarchical_tax,
'non_hierarchical_tax' => $non_hierarchical_terms,
),
'meta_input' => array(
'test_meta_key' => 'value of test_meta_key',
),
);
写笔记