Reputation: 121
So i need to get the product auto added to cart if the user visits the product page so like this
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 );
}
}
}
This works great but what i need to is to do this for any visited product so modified the code to get the current product ID like this
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 );
}
}
}
But when doing that i get this error:
Uncaught Error: Call to a member function get_id() on null. How to go about this?
Upvotes: 0
Views: 990
Reputation: 29614
The error will occur when $product
is not known. This is because the template_redirect
hook is not only executed on the single product page. So it's better to use a hook like woocommerce_single_product_summary
So you get:
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 );
Upvotes: 1