[英]Woocommerce: add to cart automatically when visiting a page (variable product IDs)
I am aware that there's already an existing function where you can add a certain product on cart upon visiting the website. 我知道,已经有一个现有功能,您可以在访问网站时在购物车中添加某些产品。 The problem is you can only do it with 1 product and I want it variable depending on the page you are visiting.
问题是您只能用1种产品来做,我希望它随您访问的页面而变化。
here's the existing code (added on functions.php file) 这是现有代码(添加到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 );
}
}
}
Inside my landing page called page-template.php, there's a custom field that echos the ID of a certain product selected. 在我的名为page-template.php的着陆页中,有一个自定义字段,该字段会回显所选特定产品的ID。 So when my user visits this page, I want this ID to replace the $product_id on the functions.php file.
因此,当我的用户访问此页面时,我希望该ID替换functions.php文件中的$ product_id。 How do I achieve this?
我该如何实现?
Many thanks in advance for the help. 预先非常感谢您的帮助。
maybe the global variable is loaded after the function. 也许全局变量是在函数之后加载的。 instead of just setting the variable initiate the function passing the variable and avoid the hook:
不仅仅是设置变量,而是通过传递变量并避免钩子来启动函数:
in functions.php: 在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 );
}
}
}
in page-template.php: 在page-template.php中:
add_product_to_cart(275);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.