网站自动发布每天60秒读懂世界文章源码2025最新版

123次阅读
没有评论

共计 4246 个字符,预计需要花费 11 分钟才能阅读完成。

ALAPI网站进行了很大的更新,原V2版本已弃用,现在使用V3版本,以下为最新的“60S读懂全世界”的API

获取token

利用alapi网站中的早报api,实现每天早8点发布wordpress文章,需要在alapi中注册并获得token,alapi地址为:https://www.alapi.cn

网站自动发布每天60秒读懂世界文章源码2025最新版

PHP代码

以下为php代码,在网站根目录下新建php文件,并将以下代码拷贝到文件中,需修改代码行的token

1、文章分类默认为“60S看世界”

2、文章的标题为“yyyy年mm月dd日,星期X,60s读懂全世界!”

3、为了方便百度收录遍历,文章的postname设置为“yyyymmdd-60s-news”

4、文章已经有了头图,博主的wp主题可在分类页面直接识别头图为缩略图,但是为了照顾有些主题只识别特色图像,博主在代码中添加了代码,将头图自动识别为特色图像,建议保留此项配置

 

[loginshow]

//由无能小子编写,二开请保留作者名称
//作者:无能小子
//无能小子博客站:https://www.wnboy.com

<?php
// 确保脚本在WordPress环境中运行
require_once(dirname(__FILE__) . '/wp-load.php');

// 定义API URL和Token
$api_url = "https://v3.alapi.cn/api/zaobao";
$api_token = 'XXXXXXXXXXXXXXXX'; // 请确保替换为您的实际API Token

// 构建带有Token的API URL(但通常API Token是作为请求头或POST数据发送的,这里假设它是作为查询参数)
$api_url_with_token = add_query_arg('token', $api_token, $api_url);

// 从API获取数据
$response = wp_remote_get($api_url_with_token);

if (is_wp_error($response)) {
    wp_die('API调用失败:' . $response->get_error_message());
}

$json_data = wp_remote_retrieve_body($response);
$data = json_decode($json_data, true);

if (isset($data['code']) && $data['code'] == 200 && $data['message'] == 'success' && isset($data['data']['news'])) {
    $news_list = $data['data']['news'];
    $head_image_url = $data['data']['head_image'] ?? ''; // 尝试获取head_image
    $combined_content = ''; // 初始化合并后的内容字符串

    // 如果head_image_url有效,则处理图像并添加到文章开头
    if (!empty($head_image_url)) {

        // 下载图像
        $image_data = wp_remote_get($head_image_url);
        if (is_wp_error($image_data)) {
            wp_die('无法下载图像:' . $image_data->get_error_message());
        }
        $image_content = wp_remote_retrieve_body($image_data);

        // 添加图像到媒体库之前的准备工作
        $upload_dir = wp_upload_dir();
        $image_filename = basename($head_image_url); // 假设URL中包含文件名
        $image_filepath = $upload_dir['path'] . '/' . $image_filename;
        file_put_contents($image_filepath, $image_content);

        // 添加图像到媒体库
        $attachment = [
            'post_mime_type' => 'image/' . pathinfo($image_filename, PATHINFO_EXTENSION), // 根据文件扩展名设置MIME类型
            'post_title'     => basename($image_filename),
            'post_content'   => '',
            'post_status'    => 'inherit'
        ];
        $attach_id = wp_insert_attachment($attachment, $image_filepath);

        // 生成附件元数据
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $image_filepath);
        wp_update_attachment_metadata($attach_id, $attach_data);

        // 获取图片的HTML代码
        $image_html = wp_get_attachment_image($attach_id, 'full'); // 或者使用其他尺寸,如'thumbnail'、'medium'、'large'等

        // 将图片添加到文章开头
        $combined_content = $image_html . '<p></p>' . $combined_content; // 添加一个空段落以分隔图像和内容(可选)
    }

    // 处理新闻内容并添加到文章中
    foreach ($news_list as $news_item) {
        // 清理新闻内容,移除开头的数字加句点,并允许安全的HTML标签
        $cleaned_content = trim(preg_replace('/^\d+。\s*/', '', $news_item)); // 根据实际情况调整字段名
        $combined_content .= '<p>' . wp_kses_post($cleaned_content) . '</p>';
    }

    // 获取当前日期和星期
    $current_date = new DateTime();
    $formatted_date = $current_date->format('Y年m月d日');
    $day_of_week_en = $current_date->format('l');
    $slug_date = $current_date->format('Ymd');


    // 定义英文星期名称到中文名称的映射
    $day_of_week_map = [
        'Monday'    => '星期一',
        'Tuesday'   => '星期二',
        'Wednesday' => '星期三',
        'Thursday'  => '星期四',
        'Friday'    => '星期五',
        'Saturday'  => '星期六',
        'Sunday'    => '星期日'
    ];

    // 获取对应的中文名称
    $day_of_week_cn = $day_of_week_map[$day_of_week_en] ?? '未知的星期';

    // 准备文章数据
    $post_data = [
        'post_title'    => "{$formatted_date} ,$day_of_week_cn ,60s读懂全世界!",
        'post_name'   => "{$slug_date}-60s-news", // 设置文章slug(别名)
        'post_content'  => $combined_content,
        'post_status'   => 'publish',
        'post_type'     => 'post',
        'post_author'   => 1,
        'post_date'     => current_time('mysql'),
    ];

    // 插入文章
    $post_id = wp_insert_post($post_data);

    if (is_wp_error($post_id)) {
        wp_die('文章发布失败:' . $post_id->get_error_message());
    } else {

        // 定义你想要使用的分类名称(这里以数组形式提供多个分类名称)
        $category_names = ['活动线报', '60s看世界']; // 替换为实际的分类名称
        // 获取分类ID数组
        $category_ids = [];
        foreach ($category_names as $category_name) {
            // 检查分类是否存在
            $term = term_exists($category_name, 'category');
            if ($term === null || $term['term_id'] == 0) {
                // 分类不存在,创建分类
                $new_term = wp_insert_term($category_name, 'category');
                if (!is_wp_error($new_term)) {
                    $category_ids[] = $new_term['term_id'];
                } else {
                    // 创建分类失败,记录错误或处理
                    error_log('创建分类失败:' . $new_term->get_error_message());
                }
            } else {
                // 分类存在,使用现有分类ID
                $category_ids[] = $term['term_id'];
            }
        }

        // 为文章设置分类
        wp_set_post_categories($post_id, $category_ids);

        // 设置文章特色图像(虽然已经在开头插入了图片,但特色图像仍然可以用于其他场合)
        set_post_thumbnail($post_id, $attach_id);

        echo '文章已成功发布,ID为:' . $post_id;
    }
} else {
//    wp_die('API响应错误:' . ($data['message'] ?? '未知错误'));
    wp_die('API调用失败,错误代码:' . $data['code'] . ',错误信息:' . $data['message']);
}
?>

[/loginshow]

 

自动化执行

在宝塔面板生成一个URL的自动化执行脚本,url填写https://你的域名/文件名.php,时间为每天7点执行(alapi中描述的是每天1点30就能看到第二天的新闻内容了,但是我感觉7点靠谱点),因为我linux运维管理工具使用的是1panel,这里就不截图了。

正文完
 0
无能小子
版权声明:本站原创文章,由 无能小子 于2025-02-05发表,共计4246字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码