![](/img/trans.png)
[英]Automatically add product to cart when visiting single product page in WooCommerce
[英]Woocommerce: add to cart automatically when visiting a page (variable product IDs)
我知道,已经有一个现有功能,您可以在访问网站时在购物车中添加某些产品。 问题是您只能用1种产品来做,我希望它随您访问的页面而变化。
这是现有代码(添加到functions.php文件中)
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 275;
$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->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 );
}
}
}
在我的名为page-template.php的着陆页中,有一个自定义字段,该字段会回显所选特定产品的ID。 因此,当我的用户访问此页面时,我希望该ID替换functions.php文件中的$ product_id。 我该如何实现?
预先非常感谢您的帮助。
也许全局变量是在函数之后加载的。 不仅仅是设置变量,而是通过传递变量并避免钩子来启动函数:
在functions.php中:
function add_product_to_cart($product_id) {
if ( ! is_admin() ) {
$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->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 );
}
}
}
在page-template.php中:
add_product_to_cart(275);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.