I'm trying to get it so that when a user visits a certain page, a specific product is added to cart, a coupon is applied, and then they are redirected to the checkout page.
This is the code I have so far, which I've added to functions.php:
function add_product_to_cart() {
$found = false;
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 ( ! $found )
WC()->cart->add_to_cart( $product_id = 8, $quantity = 1, $variation_id = 15 );
} else {
WC()->cart->add_to_cart( $product_id = 8, $quantity = 1, $variation_id = 15 );
}
}
function apply_matched_coupons() {
global $woocommerce;
$coupon_code = 'couponcodehere';
if ( $woocommerce->cart->has_discount( $coupon_code ) ) {
return;
}
foreach ($woocommerce->cart->cart_contents as $key => $values ) {
$autocoupon = array(8);
if(in_array($values['product_id'],$autocoupon)){
$woocommerce->cart->add_discount( $coupon_code );
wc_print_notices();
}
}
}
add_action( 'certain_page_redirect', 'add_product_coupon_redirect' );
function add_product_coupon_redirect() {
if( is_page('5') ) {
add_action( 'add_specific_product', 'add_product_to_cart' );
add_action( 'woocommerce_add_coupon', 'apply_matched_coupons' );
wp_redirect('http://ift.tt/2168d3f');
exit;
}
}
Nothing seems to be working. I just can't get this to work. (Note I'm a relative beginner with php.) Any thoughts?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire