如何创建默认包含一种特定产品的自定义结账表单?

问题描述 投票:0回答:1

在 WooCommerce 中,我为该页面中的产品构建了一个登陆页面,并添加了一个结账表单。

我想要的是,当客户访问此页面时,特定的定义产品将自动添加到购物车,无论购物车之前有什么商品,因此客户只能购买该特定产品。

如何做到这一点?

php wordpress woocommerce product checkout
1个回答
0
投票

假设您已为产品创建了自定义结帐登录页面,当访问该自定义登录页面时,以下代码将:

  • 如果需要,请先清空购物车
  • 然后,将定义的产品添加到购物车

在下面的代码中,您将定义相关的页面ID和所需的产品ID:


add_action('template_redirect', 'custom_checkout_landing_page_with_one_product');
function custom_checkout_landing_page_with_one_product() {
    $page_id    = 9;  // Here define your 'landing" page ID
    $product_id = 18; // Here define the desired product ID to be added to cart.

    if ( is_page( $page_id ) ) {
        if ( ! WC()->cart->is_empty() ) {
            WC()->cart->empty_cart(); // empty cart
        }
        WC()->cart->add_to_cart( $product_id ); // add the product to cart
    }
}

代码位于子主题的functions.php文件中(或插件中)。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.