Skip to content

Instantly share code, notes, and snippets.

@rawars
Created October 17, 2020 16:32
Show Gist options
  • Save rawars/24fda2f9295dbc95c0de7b560d400004 to your computer and use it in GitHub Desktop.
Save rawars/24fda2f9295dbc95c0de7b560d400004 to your computer and use it in GitHub Desktop.
Add product to cart wordpress
```
add_action( 'template_redirect', 'bbloomer_add_product_to_cart_automatically' );
function bbloomer_add_product_to_cart_automatically() {
$product_id = $_GET["pt"]; // This variable contains the code of the product that you want to add to the cart.
WC()->cart->empty_cart(); // This step is required, if what you want is to allow only one product at a time
// if cart empty, add it to cart
if ( WC()->cart->get_cart_contents_count() == 0 ) { // This step is required, if what you want is to allow only one product at a time
WC()->cart->add_to_cart( $product_id ); // Add product
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment