Skip to content

Instantly share code, notes, and snippets.

@grola
Last active March 6, 2018 09:27
Show Gist options
  • Save grola/9c89781df02100d1cd1a06110cba5df9 to your computer and use it in GitHub Desktop.
Save grola/9c89781df02100d1cd1a06110cba5df9 to your computer and use it in GitHub Desktop.
Prepare cart with products
<?php
class studiowp_add_products_to_cart {
private $products = array();
private $id = '';
public function __construct( $id = 1, $products = array() ) {
$this->products = $products;
$this->id = $id;
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
if ( isset( $_GET['studiowp_add_to_cart'] ) && $_GET['studiowp_add_to_cart'] == $this->id ) {
$cart = WC()->cart;
$cart->empty_cart();
foreach ( $this->products as $product_id ) {
$cart->add_to_cart( $product_id, 1 );
}
wp_safe_redirect( wc_get_cart_url() );
exit;
}
}
}
new studiowp_add_products_to_cart(
$id = 'my_products',
$products = array( 35, 31, 31 )
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment