问题:我需要在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