WordPress评论发布触发OneSignal推送通知的PHP代码问题排查
WordPress评论触发OneSignal通知无输出问题排查与修复
问题描述
尝试为WordPress新增评论添加动作,简单的条件判断能正常运行,但当前代码无任何结果,怀疑函数嵌套存在问题。
核心错误分析
- 函数嵌套定义问题:PHP不允许在函数内部嵌套定义另一个函数。每次执行
notify_comment时,都会尝试重新定义sendMessages,这会触发致命错误,导致代码直接终止运行,自然不会有任何输出。 - 变量作用域问题:即使嵌套定义能运行,
sendMessages函数也无法直接访问外部notify_comment函数中的$comment变量,会导致$comment未定义的错误,进而使后续逻辑无法执行。
修复方案
将sendMessages改为独立函数,通过参数传递所需的变量(如评论对象、文章ID等),避免作用域和嵌套定义的问题。同时优化代码结构,确保逻辑清晰可维护。
修正后的代码
<?php // 独立的发送通知函数,通过参数接收所需数据 function send_comment_notification($comment) { $tujuan = $comment->comment_post_ID; $permalink = get_permalink($tujuan); $posttitle = get_the_title($tujuan); $message = $comment->comment_content; $judul = "{$comment->comment_author} Mengomentari=> {$posttitle}"; $logo = get_field('propil', $tujuan); $content = array( "en" => $message, "id" => $message ); $headings = array( "en" => $judul, "id" => $judul ); $hashes_array = array( array( "id" => "read-more-button", "text" => "Balas", "icon" => "https://ppg-magetan-timur.id/wp-content/uploads/2023/02/balas.png", "url" => $permalink ), array( "id" => "read-more-button-2", "text" => "Baca komentar", "icon" => "https://ppg-magetan-timur.id/wp-content/uploads/2023/02/lihat.png", "url" => $permalink ) ); $fields = array( 'app_id' => "bbcd3d4f-6965-4b73-b82a-*************", 'included_segments' => array('Test Segment'), 'data' => array("foo" => "bar"), 'contents' => $content, 'headings' => $headings, 'url' => $permalink, 'chrome_web_image' => $logo, 'web_buttons' => $hashes_array ); $fields_json = json_encode($fields); error_log("\nJSON sent:\n" . $fields_json); // 使用error_log替代print,避免输出到前端 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications"); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8', 'Authorization: Basic NzJmMWRjZDMtMmI3Mi00NT****************' )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_json); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $response = curl_exec($ch); curl_close($ch); // 记录响应日志 error_log("\n\nJSON received:\n" . $response); $data = json_decode($response, true); error_log("Notification ID: " . ($data['id'] ?? 'N/A')); return $response; } // 评论动作钩子函数 function notify_comment($comment_id, $comment_approved) { if (1 == $comment_approved) { $comment = get_comment($comment_id); send_comment_notification($comment); } } add_action('comment_post', 'notify_comment', 10, 2); ?>
关键修改说明
- 将
sendMessages改为独立函数send_comment_notification,通过参数接收$comment对象,解决作用域问题。 - 移除函数嵌套定义,避免重复定义函数的致命错误。
- 使用
error_log替代print/print_r,避免在WordPress前端输出调试信息,同时方便在服务器日志中查看调试内容。 - 优化数组定义方式,让代码更简洁易读。
- 添加空值处理(
$data['id'] ?? 'N/A'),避免响应无id字段时出现错误。
内容的提问来源于stack exchange,提问作者Semog Jay
相关产品推荐
相关产品推荐

