Last active
June 29, 2022 14:22
-
-
Save kimcoleman/df4b8a6a67410e95ddff41837418ea7d to your computer and use it in GitHub Desktop.
A collection of recipes to force add a single product to the WooCommerce cart and redirect from the shop, single product, and cart pages right to checkout.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Always add my single product by ID to the cart if it isn't already there. | |
*/ | |
function my_woocommerce_force_add_product_to_cart() { | |
$product_id = 325; | |
$product_cart_id = WC()->cart->generate_cart_id( $product_id ); | |
if ( ! WC()->cart->find_product_in_cart( $product_cart_id ) ) { | |
// Yep, the product with ID is NOT in the cart, let's add it then! | |
WC()->cart->add_to_cart( $product_id ); | |
} | |
} | |
add_action( 'woocommerce_before_checkout_form', 'my_woocommerce_force_add_product_to_cart' ); | |
/** | |
* Redirect single product pages in WooCommerce to the cart page. | |
*/ | |
function my_woocommerce_redirect_product_pages() { | |
if ( is_admin() ) { | |
return; | |
} elseif ( | |
function_exists( 'is_product' ) && is_product() || | |
function_exists( 'is_shop' ) && is_shop() | |
) { | |
wp_safe_redirect( wc_get_checkout_url() ); | |
exit; | |
} | |
} | |
add_action( 'wp', 'my_woocommerce_redirect_product_pages', 99 ); | |
/** | |
* Skip the WooCommerce cart page and go right to checkout. | |
*/ | |
function my_woocommerce_add_to_cart_redirect() { | |
return wc_get_checkout_url(); | |
} | |
add_filter('add_to_cart_redirect', 'my_woocommerce_add_to_cart_redirect'); | |
/** | |
* Remove the WooCommerce coupon code message on checkout page. | |
*/ | |
function my_woocommerce_coupon_message( $msg, $msg_code, $instance ) { | |
if ( is_checkout() ) { | |
return ''; | |
} | |
return $msg; | |
} | |
add_filter( 'woocommerce_coupon_message', 'my_woocommerce_coupon_message', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment