Reputation: 117
I have added a product in cart programatically and then want to redirect the user to checkout page and skip the product page and cart page. Product is added successfully but it does not go to checkout page and displays a blank page with no errors. This happens only when I clear my browser cashe. second time it works fine. The user comes from a custom link to product page. I want that when user is on product page, the product should automatically added and user should be redirected to checkout page. Here is my code
add_action('template_redirect','redirect_if_cart_loaded', 10, 2);
function redirect_if_cart_loaded(){
global $woocommerce;
if(is_product() && sizeof( $woocommerce->cart->cart_contents ) == 0){
echo $pooduct_id = get_the_ID();
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
$woocommerce->cart->empty_cart();
}
// if product not found, add it
WC()->cart->add_to_cart( $pooduct_id );
echo sizeof( WC()->cart->get_cart() ); // this gives 1. means product is added
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
wp_redirect( WC()->cart->get_checkout_url() );
exit;
}
}
}
Upvotes: 0
Views: 1472
Reputation: 5303
Use
if ( !function_exists( 'wc_get_checkout_url' ) ) {
require_once '/includes/wc-core-functions.php';
}
$result = wc_get_checkout_url();
use wc_get_checkout_url instead of get_checkout_url, as get_checkout_url is deprecated
Upvotes: 1