如何为WooCommerce店铺各产品添加购物车按钮后的自定义链接代码
实现WooCommerce产品页添加可单独配置的Hotmart外部跳转按钮
要搞定这个需求,我们可以通过添加产品自定义字段+修改WooCommerce产品页输出逻辑来实现,具体步骤如下:
1. 为产品添加Hotmart链接自定义配置项
在主题的functions.php文件中插入以下代码,这样就能在产品编辑页面新增一个专属输入框,用来单独设置每个产品的Hotmart跳转链接:
// 在产品编辑页的「常规」标签下添加Hotmart链接字段 add_action('woocommerce_product_options_general_product_data', 'add_hotmart_link_field'); function add_hotmart_link_field() { woocommerce_wp_text_input( array( 'id' => '_hotmart_product_link', 'label' => __('Hotmart 产品链接', 'woocommerce'), 'placeholder' => 'https://你的Hotmart产品链接地址', 'desc_tip' => true, 'description' => __('输入该产品对应的Hotmart跳转链接', 'woocommerce') ) ); } // 保存自定义字段的链接值 add_action('woocommerce_process_product_meta', 'save_hotmart_link_field'); function save_hotmart_link_field($post_id) { $hotmart_link = isset($_POST['_hotmart_product_link']) ? sanitize_text_field($_POST['_hotmart_product_link']) : ''; update_post_meta($post_id, '_hotmart_product_link', $hotmart_link); }
2. 在「加入购物车」按钮后插入Hotmart按钮及脚本
继续在functions.php中添加以下代码,实现单个产品页中,在「加入购物车」按钮之后输出配置好的Hotmart按钮:
// 在产品页加入购物车按钮后渲染Hotmart按钮 add_action('woocommerce_after_add_to_cart_button', 'display_hotmart_button_after_add_to_cart'); function display_hotmart_button_after_add_to_cart() { // 仅在单个产品详情页执行 if (!is_product()) return; global $product; $hotmart_link = get_post_meta($product->get_id(), '_hotmart_product_link', true); // 没有配置链接则不显示按钮 if (empty($hotmart_link)) return; // 输出Hotmart代码,替换链接为自定义配置的值 ?> <script type="text/javascript"> // 优化加载逻辑:避免重复注入脚本和样式 if (typeof importHotmart !== 'function') { function importHotmart(){ var imported = document.createElement('script'); imported.src = 'https://static.hotmart.com/checkout/widget.min.js'; document.head.appendChild(imported); var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'https://static.hotmart.com/css/hotmart-fb.min.css'; document.head.appendChild(link); } importHotmart(); } </script> <a onclick="return false;" href="<?php echo esc_url($hotmart_link); ?>" class="hotmart-fb hotmart__button-checkout">Buy now</a> <?php }
3. 使用步骤
- 进入WordPress后台的产品编辑页面,在「常规」选项卡下找到新增的「Hotmart 产品链接」输入框,填入对应产品的跳转链接后保存。
- 访问该产品的前端页面,就能在「加入购物车」按钮后看到配置好的Hotmart按钮,点击后会触发对应的跳转逻辑。
注意事项
- 确保你的主题兼容WooCommerce的
woocommerce_after_add_to_cart_button钩子,如果是完全自定义的主题,可能需要直接修改产品模板文件来调整按钮位置。 - 脚本部分做了重复加载拦截,避免同一页面多次注入Hotmart的资源,提升页面加载性能。
内容的提问来源于stack exchange,提问作者Dev NAAN LLC
相关产品推荐
相关产品推荐

