请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Wordpress通过url批量自动插入文章

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
Go语言教程:时间戳发布时间:2022-05-14
下一篇:
Go语言教程:时间的格式化和解析发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap