每日一文功能是借助了每日一文api和wp_insert_post函数实现的每天自动在wp博客发布一篇美文的小功能,这个功能的所有美文内容都是由每日一文提供的,每日一文官网:https://meiriyiwen.com/,同时wp的wp_insert_post函数自带了安全判断,利用此函数自动发文不用过多担心对wp博客带来的安全问题。
自动发文源码
<?php
define( 'WP_USE_THEMES', false );
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
$web = json_decode(file_get_contents("https://interface.meiriyiwen.com/article/today?dev=1"), true);
$time = $web['data']['date']['curr'];
if ($time==date("Ymd")) {
$tt = file_get_contents('./time.txt');
if ($tt!=$time) {
$stream = fopen("./time.txt", 'w+');
fwrite($stream, "{$time}");
$tit = $web['data']['title'];
$title = decodeUnicode($tit);
$author = $web['data']['author'];
$con = $web['data']['content'];
$cont = '<p><h3>'.'作者:'.$author.'<\/h3><\/p>'.$con;
$content = decodeUnicode($cont);
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1, //对应作者 ID
'post_category' => array(2) //对应文章分类
);
// 插入文章到数据库
wp_insert_post( $my_post );
}else {
echo "文章存在";
}
}else {
echo "文章存在";
}
function decodeUnicode($str){
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return iconv("UCS-2BE","UTF-8",pack("H*", $matches[1]));'), $str);
}
?>
将上面代码保存到wp站点根目录,然后利用阿里云监控设定好访问时间,当从每日一文api中获取的文章不是当天发布的时候会自动跳过取消发文,同时当天的美文发布后会自动将日期存入txt文档,以便下一次阿里云监控时不会重复发文。
本源码使用的每日一文api地址是https://interface.meiriyiwen.com/article/today?dev=1
网友评论