You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP代码片段移动WooCommerce结账页Klaviyo订阅复选框并设为预勾选?

WooCommerce结账页Klaviyo订阅复选框调整方案

可以通过PHP代码片段实现需求,以下是具体解决方案:

代码实现

将以下代码添加到主题的functions.php文件或自定义代码插件中:

// 移除默认的Klaviyo订阅复选框
add_action('init', 'remove_klaviyo_checkout_subscribe');
function remove_klaviyo_checkout_subscribe() {
    remove_action('woocommerce_after_checkout_billing_form', array('Klaviyo_WooCommerce', 'add_checkout_optin'));
}

// 在邮箱输入框下方添加Klaviyo订阅复选框并默认勾选
add_action('woocommerce_after_checkout_billing_fields', 'add_klaviyo_checkbox_below_email', 10);
function add_klaviyo_checkbox_below_email() {
    $user_email = is_user_logged_in() ? wp_get_current_user()->user_email : '';
    $checked = 'checked="checked"';
    ?>
    <div class="klaviyo-checkout-optin" style="margin-top: 10px;">
        <label for="klaviyo_subscribe">
            <input type="checkbox" id="klaviyo_subscribe" name="klaviyo_subscribe" <?php echo $checked; ?> value="1">
            订阅我们的邮件,获取专属优惠和口腔护理小贴士
        </label>
    </div>
    <?php
}

// 处理订阅数据,同步到Klaviyo
add_action('woocommerce_checkout_update_order_meta', 'save_klaviyo_subscription');
function save_klaviyo_subscription($order_id) {
    if (isset($_POST['klaviyo_subscribe']) && $_POST['klaviyo_subscribe'] == '1') {
        $order = wc_get_order($order_id);
        $email = $order->get_billing_email();
        
        if (class_exists('Klaviyo_WooCommerce')) {
            $klaviyo = new Klaviyo_WooCommerce();
            // 替换为你的Klaviyo列表ID
            $klaviyo->add_subscriber($email, array(), 'your_list_id');
        }
    }
}

关键说明

  • 替换代码中的your_list_id为Klaviyo后台对应列表的ID,可在列表设置页面获取。
  • 若Klaviyo插件的钩子名称有更新,需查看插件源码调整remove_action中的参数。
  • 可修改style属性中的样式值,让复选框布局更贴合网站设计。
  • 测试结账流程,确认订阅状态能正确同步到Klaviyo后台。

内容的提问来源于stack exchange,提问作者Laura Nixon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:52:32