Woocommerce站点能否实现WhatsApp聊天携带产品URL自定义消息?
实现WooCommerce产品页WhatsApp带当前产品URL的自定义消息按钮
技术上完全可行,以下是具体实现方案:
一、JavaScript类实现
创建一个可复用的JS类,负责获取当前产品URL、生成自定义消息并绑定按钮点击事件:
class WhatsAppProductEnquiry { constructor(buttonSelector, messageTemplate = "I saw this on {url}. Please provide me a quote") { this.button = document.querySelector(buttonSelector); this.messageTemplate = messageTemplate; this.button && this.init(); } // 获取当前产品页面URL getCurrentProductUrl() { return window.location.href; } // 生成编码后的自定义消息 generateWhatsAppMessage() { const productUrl = this.getCurrentProductUrl(); return encodeURIComponent(this.messageTemplate.replace("{url}", productUrl)); } // 构造WhatsApp跳转链接 generateWhatsAppLink(phoneNumber) { const message = this.generateWhatsAppMessage(); return `https://api.whatsapp.com/send?phone=${phoneNumber}&text=${message}`; } // 初始化按钮点击事件 init() { // 替换为你的目标WhatsApp手机号(带国际区号,比如+861234567890) const targetPhone = "+861234567890"; this.button.addEventListener("click", (e) => { e.preventDefault(); window.open(this.generateWhatsAppLink(targetPhone), "_blank"); }); } } // 页面加载完成后初始化实例 document.addEventListener("DOMContentLoaded", () => { new WhatsAppProductEnquiry(".whatsapp-enquiry-btn"); });
二、产品页添加WhatsApp按钮
在你的WooCommerce产品页模板中,添加按钮的HTML代码(可放在产品描述下方、侧边栏等位置):
<a href="#" class="whatsapp-enquiry-btn">通过WhatsApp获取报价</a>
三、集成到WooCommerce网站
方法1:通过主题脚本加载
- 将上述JS代码保存为
whatsapp-enquiry.js文件,上传到主题目录下的js文件夹(无则新建)。 - 在主题的
functions.php文件中添加以下代码,确保仅在产品页加载该脚本:
function enqueue_whatsapp_enquiry_script() { if (is_product()) { wp_enqueue_script( 'whatsapp-product-enquiry', get_stylesheet_directory_uri() . '/js/whatsapp-enquiry.js', array(), '1.0', true ); } } add_action('wp_enqueue_scripts', 'enqueue_whatsapp_enquiry_script');
方法2:直接添加到自定义JS区域
如果主题支持自定义JS(比如WordPress后台「外观」→「自定义」→「额外JS」),可直接粘贴上述JS代码,无需文件上传。
四、扩展优化(可选)
若想在消息中加入产品标题,可修改JS类的方法:
// 新增获取产品标题的方法 getCurrentProductTitle() { const titleElement = document.querySelector("h1.product_title"); return titleElement ? titleElement.textContent.trim() : "this product"; } // 修改消息生成方法 generateWhatsAppMessage() { const productUrl = this.getCurrentProductUrl(); const productTitle = this.getCurrentProductTitle(); return encodeURIComponent(`I saw this product: ${productTitle} (${productUrl}). Please provide me a quote`); }
内容的提问来源于stack exchange,提问作者Marifur Rahaman
相关产品推荐
相关产品推荐

