在WooCommerce中访问单个产品页面时自动将产品添加到购物车中



如果用户访问产品页面,我需要将产品自动添加到购物车中,就像这样

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
global $product;
if ( ! is_admin() ) {
$product_id = 13;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}

这工作得很好,但我需要的是为任何访问过的产品做这件事,所以修改代码以获得当前产品ID,如

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
global $product;
if ( ! is_admin() ) {
$product_id = $product->get_id();
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}

但是当我这样做的时候,我得到这个错误:

Uncaught Error:在null上调用成员函数get_id()。怎么做呢?

$product不知道时会出现错误。这是因为template_redirect钩子不仅在单个产品页面上执行。所以最好使用像woocommerce_single_product_summary

这样的钩子得到:

function action_woocommerce_single_product_summary() {
// Get the global product object
global $product;

// Quantity for add to cart
$quantity = 1;

// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get ID
$product_id = $product->get_id();

// WC Cart
if ( WC()->cart ) {
// Get cart
$cart = WC()->cart;

// Cart NOT empty
if ( sizeof( $cart->get_cart() ) > 0 ) {
// Cart id
$product_cart_id = $cart->generate_cart_id( $product_id );

// Find product in cart
$in_cart = $cart->find_product_in_cart( $product_cart_id );

// NOT in cart
if ( ! $in_cart ) {
$cart->add_to_cart( $product_id, $quantity );
}
} else {
$cart->add_to_cart( $product_id, $quantity );          
}
}
}
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 10, 0 );

相关内容

  • 没有找到相关文章

最新更新