描述
如果$postarr参数的“ID”设置一个值,则将更新文章。
通过设置‘post_date’和‘post_date_gmt’键的值,可以手动设置发布日期。通过设置‘comment_status’键的值,可以关闭或打开评论。
另见
参数
$postarr
array必填-
构成要更新或插入的文章的元素数组。
ID
int文章ID。如果等于0以外的值,则将更新具有该ID的文章。默认值为0。post_author
int添加文章的用户的ID。默认值是当前用户ID。post_date
string文章的日期。默认值为当前时间。post_date_gmt
string在GMT时区中发布的日期。默认值为$post_date
。post_content
string文章内容。默认为空。post_content_filtered
string过滤后的文章内容。默认为空。post_title
string文章标题。默认为空。post_excerpt
string文章摘要。默认为空。post_status
string文章状态。默认'draft'
。post_type
string文章类型。默认值'post'
。comment_status
string文章是否可以接受评论。接受'open'
或'closed'
。
默认值是'default_comment_status'
选项的值。ping_status
string文章是否可以接受ping。接受'open'
或'closed'
.
默认值是'default_ping_status'
选项的值。post_password
string访问文章的密码。默认为空。post_name
string文章名称。默认值是创建新文章时经过净化的文章标题。to_ping
string空格或回车分隔的要ping的URL列表。
默认值为空。pinged
string空格或回车分隔的已Ping的URL列表。默认为空。post_modified
string上次修改文章的日期。默认值为当前时间。post_modified_gmt
string上次在GMT时区修改文章的日期。默认值为当前时间。post_parent
int为它所属的文章设置此项(如果有)。默认值为0。menu_order
int文章的显示顺序。默认值为0。post_mime_type
string文章的mime类型。默认为空。guid
string用于引用日志的全局唯一ID。默认为空。import_id
int插入新文章时要使用的文章ID。
如果指定,则不能与任何现有文章ID匹配。默认值为0。post_category
int[]类别ID的数组。
默认为'default_category'
选项的值。tags_input
array标签名、slug或ID的数组。默认为空。tax_input
array以分类模式的名称为键名的分类项(term)数组。
如果分类模式是分层的,则分类项列表必须是分类项ID数组或以逗号分隔的ID字符串。
如果分类模式不是分层的,分类项列表可以是包含分类项名称或slug的数组,也可以是逗号分隔的字符串。这是因为,在分层的分类模式中,子分类项可以与不同的父分类项具有相同的名称,因此连接它们的唯一方法是使用ID。默认值为空。meta_input
array文章的meta值数组,数组的键名是文章的meta键名。默认为空。page_template
string要使用的页面模板。
$wp_error
bool可选-
失败时是否返回WP_Error。
默认:
false
$fire_after_hooks
bool可选-
是否启用插入后的挂钩。
默认:
true
返回
int|WP_Error 成功时的文章ID。失败时的0值或WP_Error。
更多信息
用法
wp_insert_post( $post, $wp_error );
注意
- post_title和post_content是必填项
- post_status:如果提供“future”的post_status,则必须指定post_date,以便WordPress知道何时发布您的文章。另请参见Post Status Transitions。
- post_category:相当于调用wp_set_post_categories()。
- tags_input:相当于调用wp_set_post_tags()。
- tax_input:相当于为数组中的每个自定义分类调用wp_set_post_terms()。如果当前用户没有权限使用分类模式,则必须改用wp_set_object_terms()。
- page_template: 如果post_type为‘page’,将尝试设置page template,失败时,函数将返回一个WP_Error或0,并在调用最终操作之前停止。如果post_type不是‘page’,则忽略该参数。可以通过使用‘_wp_page_template’键调用update_post_meta(),可以为非‘page’设置页面模板。
类别
类别需要作为与数据库中的类别ID匹配的整数数组传递。即使只有一个类别分配给该文章,情况也是如此。
另请参见:wp_set_post_terms()
安全
wp_insert_post() 通过sanitize_post()传递数据,它本身处理所有必要的清理净化和验证(kses等)。
因此,你不必担心这一点。
然而,您可能希望从post_title和任何其他字段中删除HTML、JavaScript和PHP标签。令人惊讶的是,WordPress不会自动执行此操作。这可以通过使用wp_strip_all_tags()函数轻松完成,在构建前端提交后表单时尤其有用。
// Create post object $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 ) ); // Insert the post into the database wp_insert_post( $my_post );
钩子
- apply_filters( 'add_trashed_suffix_to_trashed_posts',
bool $add_trashed_suffix ,string $post_name ,int $post_ID ) -
过滤是否为与更新文章名称匹配的垃圾文章添加
__trashed
后缀。
- do_action( 'attachment_updated',
int $post_ID ,WP_Post $post_after ,WP_Post $post_before ) -
更新现有附件后触发。
- do_action( 'edit_attachment',
int $post_ID ) -
更新现有附件后触发。
- do_action( 'pre_post_update',
int $post_ID ,array $data ) -
在数据库中更新现有文章之前立即触发。
- apply_filters( 'wp_insert_attachment_data',
array $data ,array $postarr ,array $unsanitized_postarr ,bool $update ) -
过滤附件数据,在其更新或添加到数据库之前。
源码
更新日志
版本 | 描述 |
---|---|
5.6.0 | 添加了$fire_after_hooks 参数。 |
4.4.0 | 现在可以将'meta_input' 数组传递给$postarr 以添加文章meta数据。 |
4.2.0 | 添加了对文章标题、内容和摘录中的表情符号进行编码的支持。 |
2.6.0 | 添加了$wp_error 参数,以允许在出现错误时返回WP_Error。 |
1.0.0 | 开始引入 |
使用示例
插入带有自定义分类的文章和文章数meta据(自4.4.0起):
$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', ), );
只有当具有“assign_terms”访问权限的用户调用函数时,参数中的‘tax_input’才能在wp_insert_post上工作
插入文章
在调用
wp_insert_post()
之前,需要创建一个数组来传递组成文章的必要元素。wp_insert_post()
将填写这些元素的默认列表,但用户需要提供标题和内容,否则数据库写入将失败。下一个示例显示了要设置的文章标题、内容、状态、作者和文章类别。您可以添加更多的键值对,确保键与数据库中
wp_posts
表中列的名称匹配。// Gather post data. $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ) ); // Insert the post into the database. wp_insert_post( $my_post );
您还可以在插入新文章后获取新文章ID:
$post_id = wp_insert_post( $post, $wp_error );
重要的是,在使用之前,通过检查返回的值是否是WP_error,
$args = array( 'post_type' => 'my_custom_post', /*other default parameters you want to set*/ ); $post_id = wp_insert_post($args); if(!is_wp_error($post_id)){ //the post is valid }else{ //there was an error in the post insertion, echo $post_id->get_error_message(); }
正如@KieraHowe出色地注意到的,‘tax_input’需要‘assign_terms’访问。
一个快速的解决方案是:
wp_set_object_terms( $post_id, array( $term_id1, $term_id2 ), 'tax_slug' );
还应说明post_template参数。
应该使用完整的文件名进行设置,例如“templatefilename.php”。
这一澄清将帮助开发人员尝试将模板绑定到页面。
默认情况下,
wp_insert_post
不会插入空文章。如果您正在传递一个ID
并期望它返回到wp_update_post
,这可能会导致意外的问题。例如,以下操作将不起作用:wp_insert_post( array( 'ID' => 2, 'post_parent' => 1 ) );
您需要直接调用
wp_update_post
。wp_update_post( array( 'ID' => 2, 'post_parent' => 1 ) );
保存包含斜杠的数据时,请记住添加额外的斜杠,因为
wp_insert_post
会清除一次斜杠。$regex = '(\b16-\d{3}\b)'; $post_data = array( 'post_title' => 'Test regex', 'post_content' => $regex, 'post_type' => 'post', ); $post_id = wp_insert_post( $post_data );
将存储
(b16-d{3}b)
。要解决此问题,请使用wp_slash()
:$regex = '(\b16-\d{3}\b)'; $post_data = array( 'post_title' => 'Test regex', 'post_content' => wp_slash( $regex ), 'post_type' => 'post', ); $post_id = wp_insert_post( $post_data );
post_date
和post_date_gmt
输入的格式是Y-m-d H:i:s
,例如2019-01-01 01:01:01
。您可以使用PHP的date
函数,如下所示:wp_insert_post( array( 'post_date' => date( 'Y-m-d H:i:s', time() ), // etc ) );
关于分类模式参数
参数:'tax_input' (array) Array of taxonomy terms keyed by their taxonomy name. Default empty.
参数‘tax_input’的描述没有明确说明,到目前为止没有给出任何示例,因此我想在这里补充说明确切的含义和示例。
根据‘wp_insert_post()’的源代码,‘tax_input’由函数‘wp_set_post_terms()’添加。所以我参考了它的描述,下面是使用它的示例:
'tax_input' => array( $taxomony => $tags )
- $taxomony – (string) 分类模式名称 $tags – (string|array) 要为文章设置的分类项数组,或用逗号分隔的字符串。 (tags)
例如
'something1, something2, something3'
或
array( 30, 40, 50 )
或
array( 'something1', 'something2', 'something3' )
- 有分层级的分类模式 (类别) 必须始终传递ID,而不是名称,以便同名但父级不同的子级不会混淆。例如
array( 30, 40, 50 )
测试:我已经在一个带有自定义类别(分类模式)名称的自定义文章类型中使用wp_update_post()对其进行了个人测试
- $taxomony – (string) 分类模式名称 $tags – (string|array) 要为文章设置的分类项数组,或用逗号分隔的字符串。 (tags)
使用自定义文章类型添加分类和meta字段值。
对于分类:
请确保分类名称是tax_input数组的键。而分类的ID数组是该键的值,如下面的示例所示。对于meta值:
您可以将meta值名称作为键传递,将meta值作为键值传递。$post_arr = array( 'post_title' => esc_html($video_title), 'post_content' => $video_description, 'post_status' => 'draft', 'post_author' => $user_id, 'post_type' => 'videos', 'tax_input' => array( "video_category" => $taxnomy_ids //Video Cateogry is Taxnmony Name and being used as key of array. ), 'meta_input' => array( 'wc_video_url' => $video_url, 'wc_product' => $video_product ), );
如果您正在创建一篇文章,但文章ID尚不存在,则使用
'ID' => your_number
不会创建新的文章。它将返回空白,因为它搜索了ID,但它不存在。而是像这样使用
'import_id'
:$args = array( 'import_id' => your_custom_integer, // this designates the custom post ID you want to use! make sure it's unique 'post_type' => 'your_post_type', 'post_status' => 'publish', 'content' => 'your_content', 'meta_input' => array( 'product_data' => 'if_you_want_this' ) ); $id = wp_insert_post($args);
防止重复文章
// Product Title $post_title = 'Test Product'; // Add Product $new_post = array( 'post_title' => $post_title, 'post_type' => 'product', 'post_staus' => 'draft', 'post_content' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', 'post_excerpt' => 'Lorem Ipsum is simply dummy text' ); // Catch post ID $post_id = post_exists( $post_title ) or wp_insert_post( $new_post );
直接插入id为32的现有附件作为文章缩略图。
$thumbnail_id = 32; $args = array( 'post_type' => 'post', 'post_title' => 'Some title', 'post_content' => 'Some content', '_thumbnail_id' => $thumbnail_id, ); wp_insert_post( $args );
为自定义文章类型创建文章:
$id = wp_insert_post(array('post_title'=>'random', 'post_type'=>'custom_post', 'post_content'=>'demo text'));
注意当使用wp_insert_post()更新文章时,如果您没有明确指定post_status,它会将其改回“草稿”。
我最终使用了wp_update_post()。
要使用此函数,您应该
$_POST
$post_title = $_POST['title']; $post_description = $_POST['content']; $post_posted_id = $_POST['user_id']; $post_categories = $_POST['term']; $post_options = array(); if( !empty($post_description) ) { $post_options['post_content'] = wp_strip_all_tags(post_description); } if( !empty($post_title) ) { $post_options['post_title'] = wp_strip_all_tags($post_title); // Then start to add new post $post_id = wp_insert_post($post_options); // Then return JSON in case you are using AJAX if( !is_wp_error($post_id) ) { wp_send_json_success(array('post_id' => $post_id), 200); } else { wp_send_json_error($post_id->get_error_message()); } }
第二件事,如果您推送多个参数,如选中多个复选框,您应该知道如何推送到数组:
示例标记:
<?php // Existing Bootstrap 4 markup if( !empty($languages) ) : ?> <?php foreach($languages as $key => $language) : ?> <div class="form-check"> <input class="form-check-input" type="checkbox" value="<?php echo $language['id']; ?>" id="term[language][<?php echo $key; ?>]" name="term[language][]"> <label class="form-check-label" for="term[language][<?php echo $key; ?>]"><?php echo $language['name']; ?></label> </div> <?php endforeach; ?> <?php endif; // The result you got term[language] = [11, 13, 14]; ?>
我们应该检查并使用此函数以确保其工作:
<?php // Function hint: wp_ajax_ // Function hint: wp_ajax_nopriv_ $post_terms = $_POST['term']; if( !empty($post_terms) ) { foreach($post_terms as $key => $category) { if( $post_options['tax_input'][$key] !== '' ) { $post_options['tax_input'][$key] = array($category); } else { array_push($post_options['tax_input'][$key], $category); } } } ?>
此代码段创建了一篇文章,代码在创建之前检查该文章是否已存在。
function create_wordpress_post_with_code() { // Set the post ID to -1. This sets to no action at moment $post_id = -1; // Set the Author, Slug, title and content of the new post $author_id = 1; $slug = 'wordpress-post-created-with-code'; $title = 'WordPress post created whith code'; $content = 'This is the content of the post that we are creating right now with code. More text: I motsetning til hva mange tror, er ikke Lorem Ipsum bare tilfeldig tekst. Dets røtter springer helt tilbake til et stykke klassisk latinsk litteratur fra 45 år f.kr., hvilket gjør det over 2000 år gammelt. Richard McClintock - professor i latin ved Hampden-Sydney College i Virginia, USA - slo opp flere av de mer obskure latinske ordene, consectetur, fra en del av Lorem Ipsum, og fant dets utvilsomme opprinnelse gjennom å studere bruken av disse ordene i klassisk litteratur. Lorem Ipsum kommer fra seksjon 1.10.32 og 1.10.33 i "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) av Cicero, skrevet i år 45 f.kr. Boken er en avhandling om teorier rundt etikk, og var veldig populær under renessansen. Den første linjen av Lorem Ipsum, "Lorem Ipsum dolor sit amet...", er hentet fra en linje i seksjon 1.10.32.'; // Cheks if doen't exists a post with slug "wordpress-post-created-with-code". if( !post_exists_by_slug( $slug ) ) { // Set the post ID $post_id = wp_insert_post( array( 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $slug, 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'post' ) ); } else { // Set pos_id to -2 becouse there is a post with this slug. $post_id = -2; } // end if } // end oaf_create_post_with_code add_filter( 'after_setup_theme', 'create_wordpress_post_with_code' ); /** * post_exists_by_slug. * * @return mixed boolean false if no post exists; post ID otherwise. */ function post_exists_by_slug( $post_slug ) { $args_posts = array( 'post_type' => 'post', 'post_status' => 'any', 'name' => $post_slug, 'posts_per_page' => 1, ); $loop_posts = new WP_Query( $args_posts ); if ( ! $loop_posts->have_posts() ) { return false; } else { $loop_posts->the_post(); return $loop_posts->post->ID; } }