下面由WordPress教程欄目給大家介紹通過WordPress內(nèi)置函數(shù)批量添加文章的方法,希望對(duì)需要的朋友有所幫助!
最近業(yè)務(wù)需要在網(wǎng)站上批量添加大量的文章。一篇一篇地手動(dòng)添加絕對(duì)會(huì)搞死我,所以,我就開始尋找批量添加的方法。其實(shí),文章的相關(guān)內(nèi)容都已經(jīng)在本地的數(shù)據(jù)庫里了。我最先想到的方法是通過sql語句直接把數(shù)據(jù)導(dǎo)入線上的庫里。
于是我通過
INSERT INTO target_table (key1, key2...) SELECT key1', key2' ... FROM source_table;
將數(shù)據(jù)插入到了線上的表中。打開頁面一看,全是亂碼。于是,我又在插入前設(shè)置了一下編碼,還是有問題。
由于我是一個(gè)不善長(zhǎng)sql的人,我調(diào)整了一下策略。偶然間,我發(fā)現(xiàn)了一個(gè)WordPress的內(nèi)置函數(shù) ‘wp_insert_post’。嗯,就是他了。
于是,我將目標(biāo)數(shù)據(jù)導(dǎo)出成php_array,然后引入到我的腳本中,通過wp_insert_post函數(shù)添加到數(shù)據(jù)庫中。
foreach( $php_array as $item ){ $arg = array( 'post_title' => $item['title'], 'post_content' => $item['content'], 'post_excerpt' => $item['excerpt'], 'post_type' => 'post', 'post_status' => 'public', 'meta_input' => array( 'meta_key' => 'meta_value' ) ); wp_insert_post( $arg ); }
這樣,就通過WordPress“合法”的方式批量添加了文章,而且meta_input中可以添加自定義欄目,可以說非常棒了。
wp_insert_post具體的使用方法參見:官方文檔
https://developer.wordpress.org/reference/functions/wp_insert_post/