如何通过wp_redirect实现WhatsApp URL消息换行(WooCommerce场景)
解决方案:保留wp_redirect实现WhatsApp通知换行
问题根源
wp_redirect内部会调用wp_sanitize_redirect函数,这个函数会主动移除URL中的%0A(编码后的换行符)——哪怕你设置strip_new_lines为false也没用,因为这个参数仅控制是否移除原始的\n字符,而非编码后的%0A。
最优方案:占位符替换法
通过临时占位符绕过wp_sanitize_redirect的过滤,再在跳转前恢复换行符编码,不影响全局跳转逻辑:
// 1. 获取订单对象并生成带换行的通知内容 $order = wc_get_order($order_id); // 替换为你的实际订单ID或对象 $message = sprintf( "新订单通知:\n订单号:%s\n客户姓名:%s\n订单金额:%s", $order->get_id(), $order->get_formatted_billing_full_name(), $order->get_formatted_order_total() ); // 2. 编码消息,将%0A替换为自定义占位符(避免被过滤) $encoded_msg = urlencode($message); $encoded_msg = str_replace('%0A', '[[NEWLINE]]', $encoded_msg); // 3. 构建WhatsApp跳转URL $whatsapp_url = "https://api.whatsapp.com/send?phone=+你的目标手机号&text={$encoded_msg}"; // 4. 添加钩子,在wp_redirect发送前恢复%0A add_filter('wp_redirect', function($location) { return str_replace('[[NEWLINE]]', '%0A', $location); }, 99); // 高优先级确保最后执行 // 5. 执行跳转(必须加exit/die终止后续代码) wp_redirect($whatsapp_url); exit;
备选方案:全局允许URL中的换行编码
如果你希望所有wp_redirect跳转都保留%0A,可以直接过滤wp_sanitize_redirect的结果:
add_filter('wp_sanitize_redirect', function($redirect_url) { // 恢复被默认过滤掉的%0A(换行)和%0D(回车) return preg_replace('/(%0A|%0D)/', '$1', $redirect_url); }, 11); // 优先级高于默认的10,确保在默认处理后执行 // 之后正常生成跳转URL即可,无需占位符 $message = sprintf(/* 带换行的通知内容 */); $encoded_msg = urlencode($message); $whatsapp_url = "https://api.whatsapp.com/send?phone=+你的目标手机号&text={$encoded_msg}"; wp_redirect($whatsapp_url); exit;
注意事项
- 跳转后必须调用
exit或die,避免WordPress继续执行后续代码导致跳转失效。 - 占位符建议使用不会出现在正常URL中的字符串,防止意外替换。
内容的提问来源于stack exchange,提问作者Faiz Ali
相关产品推荐
相关产品推荐

