【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个字)、文章链接。测试效果如下:

相关推荐
星光一影8 小时前
打车/网约车、代驾、顺风车/拼车、货运、租车等多种出行服务的一站式解决方案
mysql·微信小程序·php·uniapp·html5·web app
JSON_L9 小时前
Fastadmin中使用小程序登录
小程序·php·fastadmin
诸葛务农9 小时前
智慧康养人形机器人——银发科技的革命者及在日本超老龄化社会的实验(上)
科技·机器人
星光一影10 小时前
悬赏任务平台/拉新地推系统源码
redis·mysql·小程序·php·uniapp·html5
是孑然呀11 小时前
【钉钉多元表格(自动化)】钉钉群根据表格 自动推送当天值日生信息
运维·自动化·钉钉
报错小能手13 小时前
计算机网络自顶向下方法24——运输层 可靠数据传输 超时间隔加倍 快速重传 是回退n步还是选择重传
网络·计算机网络·php
未来智慧谷13 小时前
OpenAI押注的NEO人形机器人:技术拆解与消费级人形机器人落地启示
机器人·openai·人形机器人neo
IT小哥哥呀14 小时前
Node.js 实现企业内部消息通知系统(钉钉/企业微信机器人)
node.js·钉钉·企业微信·webhook·后端开发·自动化通知·mysql实战
JaguarJack15 小时前
PHP 现代特性速查 写出更简洁安全的代码(完结篇)
后端·php
APIshop1 天前
PHP:一种强大的服务器端脚本语言
服务器·php