Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Last active August 12, 2018 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finalwebsites/6fcc0c7bad81eee892cfe849788bd5bb to your computer and use it in GitHub Desktop.
Save finalwebsites/6fcc0c7bad81eee892cfe849788bd5bb to your computer and use it in GitHub Desktop.
This snippet for WooCommerce will force your customers to login or register before they can enter the checkout page.
<?php
/*
Redirect customers from the checkout page to the my account page
Conditions: not logged in, no guest checkout and not yes received an order
The query var redirect_to_checkout, this one is used to redirect back to the checkout after login or registration
*/
function checkout_template_redirect() {
global $wp;
$guest = get_query_var( 'guest', '' );
$check_out_url = get_permalink( get_option('woocommerce_checkout_page_id') );
if ( !is_user_logged_in() && is_checkout() && $guest == '' && empty($wp->query_vars['order-received']) ) {
wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ).'?redirect_to_checkout=1' );
exit;
}
}
add_action( 'template_redirect', 'checkout_template_redirect' );
/*
This function creates a guest checkout link below the registration form.
*/
function add_redirect_field(){
echo '
<p><a href="'.get_permalink( get_option('woocommerce_checkout_page_id') ).'?guest=1">No thanks, I don\'t need an account.</a></p>';
}
add_action('woocommerce_register_form_end', 'add_redirect_field');
/*
After login or registration the function will change the redirect URL to send the customer back to the checkout page
*/
function wc_login_register_redirect( $redirect_to ) {
$redirect_to_checkout = get_query_var( 'redirect_to_checkout', '' );
if (!WC()->cart->is_empty() && $redirect_to_checkout != '') {
$redirect_to = get_permalink( get_option('woocommerce_checkout_page_id') );
}
return $redirect_to;
}
add_filter('woocommerce_login_redirect', 'wc_login_register_redirect');
add_filter('woocommerce_registration_redirect', 'wc_login_register_redirect');
/*
Register some query vars
*/
add_filter('query_vars', 'add_my_vars');
function add_my_vars($public_query_vars) {
$public_query_vars[] = 'guest';
$public_query_vars[] = 'redirect_to_checkout';
return $public_query_vars;
}
@finalwebsites
Copy link
Author

How to use?

  1. Add this code to your functions.php file
  2. Enabled guest checkout
  3. Disable registration and login for the checkout page

Optional:
Hide the registration form on your my account page if the cart is empty
for example by change the code for the form-login.php file:
<?php if ( get_option( 'woocommerce_enable_myaccount_registration' ) === 'yes' && !WC()->cart->is_empty() ) { ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment