如何在WordPress发布文章时将数据发送至外部API
WordPress发布文章时推送数据到外部API的实现方案
一、代码存放位置
- 推荐:自定义插件:创建一个简单的自定义插件,避免主题更新导致代码丢失。新建文件
wp-post-to-api.php放在wp-content/plugins/目录下,添加插件头部注释后激活即可:<?php /* Plugin Name: WordPress Post to External API Description: 推送发布的文章数据到外部API Version: 1.0 Author: Your Name */ // 核心代码放在这里 - 临时测试:主题functions.php:如果只是临时验证功能,可以把代码加到当前激活主题的
functions.php文件,但主题更新后代码会被覆盖,不推荐长期使用。
二、拦截文章发布事件
WordPress提供两个常用钩子监听文章发布状态:
publish_post:仅在文章首次从草稿/待审转为发布状态时触发transition_post_status:监听所有文章状态变化,支持区分“首次发布”和“更新后重新发布”的场景(更灵活)
推荐使用transition_post_status,覆盖更多业务场景。
三、核心实现代码
使用WordPress自带的wp_remote_put()函数发送请求(比原生curl更兼容WordPress环境),示例代码如下:
// 监听文章状态变更事件 add_action('transition_post_status', function($new_status, $old_status, $post) { // 仅处理文章类型(排除页面、自定义文章类型等,按需调整) if ($post->post_type !== 'post') return; // 仅在状态转为发布时触发(首次发布或更新后发布都触发,按需修改条件) if ($new_status === 'publish') { // 1. 收集需要推送的文章数据 $post_data = [ 'post_id' => $post->ID, 'title' => get_the_title($post->ID), 'content' => apply_filters('the_content', $post->post_content), // 处理短代码、格式 'excerpt' => $post->post_excerpt, 'featured_image_url' => get_the_post_thumbnail_url($post->ID, 'full'), 'published_time' => $post->post_date_gmt, 'categories' => wp_list_pluck(get_the_category($post->ID), 'name'), 'tags' => wp_list_pluck(get_the_tags($post->ID), 'name') ?: [] ]; // 2. 配置API请求参数 $api_endpoint = 'https://your-api-domain.com/target-path'; // 替换为你的API地址 $request_headers = [ 'Content-Type' => 'application/json', // 若API需要认证,添加对应头部,例如: // 'Authorization' => 'Bearer YOUR_API_TOKEN' ]; $request_body = json_encode($post_data); // 3. 发送PUT请求 $response = wp_remote_put($api_endpoint, [ 'headers' => $request_headers, 'body' => $request_body, 'timeout' => 15, // 设置超时时间,避免阻塞后台 'sslverify' => true // 生产环境建议开启,测试环境可设为false跳过SSL验证 ]); // 可选:记录请求日志,方便排查问题 if (is_wp_error($response)) { error_log('[Post to API] 请求失败: ' . $response->get_error_message()); } else { $status_code = wp_remote_retrieve_response_code($response); if (!in_array($status_code, [200, 201])) { error_log('[Post to API] 返回错误状态码: ' . $status_code . ',响应内容: ' . wp_remote_retrieve_body($response)); } } } }, 10, 3);
四、关键注意事项
- 异步请求优化:如果API响应较慢,会导致文章发布卡顿,建议用
wp_schedule_single_event将请求转为异步执行,或者使用Action Scheduler插件处理异步任务。 - 数据适配:根据外部API的字段要求调整
$post_data的结构,比如重命名字段、过滤不需要的内容。 - 调试与日志:在
wp-config.php中开启调试日志(define('WP_DEBUG_LOG', true);),方便查看请求失败的原因。 - 权限控制:可以通过判断
$old_status !== 'publish',限制仅在首次发布时推送,避免重复提交数据。
内容的提问来源于stack exchange,提问作者Luca Pelosi
相关产品推荐
相关产品推荐

