問題描述
我使用函數 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″ 的搜索,找不到任何結果。
最佳解決方案
wp_insert_posts()的這一部分給了它:
if ( ! empty( $postarr['meta_input'] ) ) {
foreach ( $postarr['meta_input'] as $field => $value ) {
update_post_meta( $post_ID, $field, $value );
}
}
在那裏我們看到後期元字段如何更新/添加 update_post_meta()。
以下是 meta_input 的內聯描述:
Array of post meta values keyed by their post meta key. Default empty.
這是添加到 WordPress 4.4 和這裏的相關票 #20451 瞭解更多信息。
請注意,使用元鍵_test 前面的下劃線將在後編輯屏幕中將其隱藏自定義字段 metabox 。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。