【WordPress】发布文章时自动通过机器人推送到钉钉

在您的主题下functions.php中添加如下代码:

bash 复制代码
function wpso_dingding_publish_notify($post_ID) {
    // 获取文章对象
    $post = get_post($post_ID);
    
    // 检查是否是文章首次发布(即不是修订版)
    if (get_post_status($post_ID) == 'publish' && !get_post_meta($post_ID, '_wpso_dingding_sent', true)) {
        // 文章的标题、人工摘要和链接
        $title = get_the_title($post_ID);
        $excerpt = $post->post_excerpt;  // 获取文章的人工设置摘要
        if (empty($excerpt)) {
            // 如果没有设置摘要,使用文章内容的前20个字作为摘要
            $excerpt = wp_trim_words(get_post_field('post_content', $post_ID), 20);
        }
        $url = get_permalink($post_ID);
        
        // 发送的消息内容
        $text = get_bloginfo('name') . ' 上有新的文章发布啦!!';
        $desp = '文章标题:' . $title . "\n" . '文章摘要:' . $excerpt . "\n" . '文章链接:' . $url;

        // 钉钉机器人的 Access Token
        $access_token = '你的Token';
        
        // 构造发送数据
        $data = array(
            'msgtype' => 'text',
            'text' => array(
                'content' => $text . "\n" . $desp
            )
        );
        
        // 将数据编码为JSON格式
        $json_data = json_encode($data, JSON_UNESCAPED_UNICODE);
        
        // 配置HTTP请求
        $opts = array('http' => array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/json',
            'content' => $json_data
        ));
        
        // 创建HTTP上下文
        $context = stream_context_create($opts);
        
        // 发送钉钉推送
        $result = file_get_contents('https://oapi.dingtalk.com/robot/send?access_token=' . $access_token, false, $context);
        
        // 标记文章已发送,避免重复发送
        update_post_meta($post_ID, '_wpso_dingding_sent', true);
    }
}
add_action('publish_post', 'wpso_dingding_publish_notify');

即可实现自动推送,推送内容包括文章标题、文章设置的人工摘要(若无则提取文章内容前20个字)、文章链接。测试效果如下:

相关推荐
catchadmin2 小时前
PHP 快速集成 ChatGPT 用 AI 让你的应用更聪明
人工智能·后端·chatgpt·php
Q_Q5110082858 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
2503_924806858 小时前
动态IP使用中 报错407 怎么办???
服务器·tcp/ip·php
haing20199 小时前
SCARA 机器人轨迹运动奇异点规避方法
机器人·轨迹规划·奇异位置
非凡的世界10 小时前
Telegram机器人Token和ChatID获取教程
机器人·telegram
Deepoch10 小时前
Deepoc具身智能模型:为传统机器人注入“灵魂”,重塑建筑施工现场安全新范式
人工智能·科技·机器人·人机交互·具身智能
该用户已不存在12 小时前
PHP、Python、Node.js,谁能称霸2025?
python·node.js·php
Q_Q51100828516 小时前
python+nodejs+springboot在线车辆租赁信息管理信息可视化系统
spring boot·python·信息可视化·django·flask·node.js·php
_Re.16 小时前
DSC 归档配置相关
数据库·oracle·php
xwz小王子16 小时前
OpenAI 回归机器人:想把大模型推向物理世界
数据挖掘·回归·机器人