Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active July 15, 2021 14:19
Show Gist options
  • Save jorpdesigns/b0e81d34c2875fc43844df5cbf05234a to your computer and use it in GitHub Desktop.
Save jorpdesigns/b0e81d34c2875fc43844df5cbf05234a to your computer and use it in GitHub Desktop.
Snippet to automatically add products to WooCommerce cart
<?php
// FUNCTION TO CHECK IF ITEM IS IN CART
function item_in_cart( $product_id ) {
$found = false;
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $value ) {
$product = $value['data'];
if ( $product->get_id() == $product_id ) {
$found = true;
break;
}
}
}
return $found;
}
// ADD PRODUCT TO CART BY DEFAULT
add_action( 'init', 'aaptc_by_default' );
function aaptc_by_default() {
if ( ! is_admin() ) {
$product_id = 12986; // Replace with id of product you want to add
if ( ! item_in_cart( $product_id ) )
WC()->cart->add_to_cart( $product_id );
}
}
// ADD PRODUCT B TO CART IF PRODUCT A IS IN CART
add_action( 'woocommerce_add_to_cart', 'aaptc_based_on_product', 10, 2 );
function aaptc_based_on_product( $item_key, $product_id ) {
if ( ! is_admin() ) {
$productA = 34; // Replace with id of product a
$productB = 56; // Replace with id of product b
if ( item_in_cart( $productA ) ) {
if ( ! item_in_cart( $productB ) )
WC()->cart->add_to_cart( $productB );
}
}
}
// ADD PRODUCT TO CART IF CART TOTAL REACHES 500
add_action( 'template_redirect', 'aaptc_based_on_total' );
function aaptc_based_on_total() {
$cart_total = 500;
if ( WC()->cart->cart_contents_total >= $cart_total ) {
if ( ! is_admin() ) {
$product_id = 12986; // Replace with id of product you want to add
if ( ! item_in_cart( $product_id ) )
WC()->cart->add_to_cart( $product_id );
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment