wp_insert_post()中的“ meta_input”参数用于什么?


10

我正在使用wp_insert_post()函数将一些帖子插入wordpress中。

我想在每篇文章中插入一些自定义字段并阅读文档,尽管我使用了meta_info参数,但我尝试过这样的事情:

$data = array(
        'post_author' => 1,
        'post_status' => 'publish',
        'post_title' => $post->getTitle(),
        'post_content' => $post->getContent(),
        'post_category' => $post->getCategory(),
        'tags_input' => $post->getTags(),
        'meta_input' => array( "_test" => "testx1" )
);

$postID = wp_insert_post( $data );

该帖子会正确插入并且也有标签。但是没有添加自定义字段。我知道我可以使用add_post_meta()添加它们,但我仍然想知道meta_input参数的用途,因为在插入帖子后我在数据库中搜索了“ testx1”,但找不到任何结果。

Answers:


7

的这一部分wp_insert_posts()给出了它:

  if ( ! empty( $postarr['meta_input'] ) ) {
        foreach ( $postarr['meta_input'] as $field => $value ) {
            update_post_meta( $post_ID, $field, $value );
        }
  } 

我们在其中看到如何使用来更新/添加post meta字段update_post_meta()

这是的内联描述meta_input

由后置元键键入的后置元值数组。默认为空。

这已在WordPress 4.4中添加,有关更多信息,请参见此处的相关故障#20451

请注意,在meta键前面使用下划线_test会将其从帖子编辑屏幕中的自定义字段 metabox 隐藏。


哦,我正在测试的wp im是4.3,非常感谢。
streel

0

我这样做的方式是通过term_id而不是ug弹,它的工作原理是:

//insert Art items into database
$arr = array('item 1', 'item 2');
// $arr = array('art item 1', 'art item 2');

foreach ($arr as $a) { 
    wp_insert_post(array(
    //essentials
    //'ID'      => 1131,
    'post_author'       => 1,
    'post_title'        => $a,
    'post_type'         => 'post',
    'post_content'      => 'Something...',
    'post_status'       => 'publish',
    'post_name'         => 'post name',
    'meta_input'        => array( //(array) Array of post meta values keyed by their post meta key. Default empty.
        'city'     => '',// 'name' => $post['name']
        'country'  => ''// 'city' => $post['city']
    ),
    'tax_input'    => array(
        'category' => array(33,32), //id numbers work, slugs tend to be ignored !!!
        'post_tag' => array('one', 'two') //for tags slugs seem to work
    ),//(array) Array of taxonomy terms keyed by their taxonomy name. Default empty. Equivalent to calling wp_set_post_terms() / wp_set_object_terms()
    //'tags_input'  => array('una', 'trei'), //(array) Array of tag names, slugs, or IDs. Default empty. Equivalent to calling wp_set_post_tags().
    ), true);   
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.