简体   繁体   中英

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.

here's the existing code (added on functions.php file)

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. So when my user visits this page, I want this ID to replace the $product_id on the functions.php file. 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:

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:

add_product_to_cart(275);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM