如何在 WooCommerce 中实现自动添加到购物车功能?

tencent promotion
原创作者: Fengjiajun

如何在 WooCommerce 中实现自动添加到购物车功能?

由于业务需要,想在Woocommerce中实现这样一个功能:
当点击一个链接比如https://fengjiajun.com/checkout?id=12时,自动将ID为12的产品添加到购物车并跳转到结账页面;

实现方式如下,将下面代码添加到WordPress主题目录下的functions.php文件即可:

//auto add to cart and redirect to checkout by id with url
function auto_add_product_to_cart_and_redirect() {
    if (isset($_GET['id'])) {
        $product_id = intval($_GET['id']);
        if (wc_get_product($product_id)) {
            WC()->cart->empty_cart();
            WC()->cart->add_to_cart($product_id);
            wp_redirect(wc_get_checkout_url());
            exit;
        }
    }
}
add_action('template_redirect', 'auto_add_product_to_cart_and_redirect');

该功能应用场景:
谷歌GMC有一个【快速结账】模块,添加上面的代码后,我们就可以使用这个功能了: