問題:我需要在wordpress中批量自動插入文章。實際上是想就是可以通過一個url來發布文章,例如: www.mypage.com/insertnewpost.php?title=blah&content=blahblahblah&category=1,2,3。下麵的代碼隻能在主題文件functions.php中正常運行:
include '../../../wp-includes/post.php';
global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);
當我使用上麵的代碼創建一個新的頁麵的時候(insertnewposts.php), 運行會報錯:
Fatal error: Call to undefined function add_action() in xxx/wordpress/wp-includes/post.php on line xxx
這是怎麽回事?
解決方案:如果想讓下麵的代碼能正常運行:
global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);
我們需要確保wordpress的運行環境和依賴的資源已經全部啟動或者就緒。也就是說wordpress的bootstrap過程,這個過程中wordpress的各種
配置將會導入內存,同時也包括上麵問題中 add_action這樣的核心函數。
所以,要想讓上麵的代碼
wp_insert_post()
能自動插入文章,我們啟動wordpress的bootstrap就可以了。創建一個包含下麵代碼的文件www.yourdomain.com/wpinstalldir/autoposts.php:
<?php
/**
* Writes new posts into wordpress programatically
*
* @package WordPress
*/
/** Make sure that the WordPress bootstrap has run before continuing. */
require(dirname(__FILE__) . '/wp-load.php');
global $user_ID;
$new_post = array(
'post_title' => 'My New Post',
'post_content' => 'Lorem ipsum dolor sit amet...',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);
?>
然後執行:www.yourdomain.com/wpinstalldir/autoposts.php這個頁麵就可以成功創建或者插入文章了。
也就是加入下麵的頭文件引用即可:
require(dirname(__FILE__) . '/wp-load.php');
具體在哪個目錄並不是必須的,require中填上wp-load.php文件絕對路徑即可。
【參考文獻】
[1] http://wordpress.stackexchange.com/questions/20590/wordpress-inserting-posts-programatically-through-a-url