Advertisement
wpgenie

add to cart redirects to login page

Nov 23rd, 2020 (edited)
1,105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.27 KB | None | 0 0
  1. /*
  2.  
  3. Code snippet that automatically redirects user to login page if user tries to add tickets without being logged in.
  4.  
  5. Code should go to your child theme functions.php file.
  6.  
  7. */
  8.  
  9. add_action( 'woocommerce_add_to_cart_validation', 'custom_redirect_to_login_page', 5, 4);
  10.  
  11. function custom_redirect_to_login_page($pass, $product_id, $quantity, $variation_id = 0){
  12.     if ( is_user_logged_in() ){
  13.         return $pass;
  14.     }
  15.     if ( function_exists( 'wc_get_product' ) ) {
  16.  
  17.         $product = wc_get_product( $product_id );
  18.     } else {
  19.         $product = new WC_Product( $product_id );
  20.     }
  21.     if ( $product->get_type() == 'lottery' ) {
  22.         $max_tickets_per_user = $product->get_max_tickets_per_user() ? $product->get_max_tickets_per_user() : false;
  23.         if ( $max_tickets_per_user == false  OR $max_tickets_per_user == $product->get_max_tickets() ) {
  24.                     return true;
  25.         }
  26.         $redirect = add_query_arg( 'redirect_to', get_permalink( $product->get_id() ), get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) );
  27.         wp_redirect( $redirect );
  28.         exit();
  29.     }
  30.  
  31. }
  32. function custom_login_redirect( $redirect_to ){
  33.     if( isset( $_REQUEST['redirect_to'] ) ) {
  34.         return $_REQUEST['redirect_to'];
  35.     } else {
  36.         return $redirect_to;
  37.     }
  38. }
  39. add_filter( 'login_redirect', 'custom_login_redirect');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement