skip to Main Content

I have a digital download site running on WordPress/WooCommerce that requires users to be logged in to buy products. There is a login/register button displayed for logged-out users instead of the ‘Buy’ button on product pages as seen here: https://prnt.sc/1rc03lw. I’m trying to redirect users after they’ve logged in or registered back to the previous page but only if that previous page was a product page.

Here is the code I’m currently using which saves the referring URL and then executes a redirect. The redirect works but, I’m trying to limit it to only redirect if the referer URL was a product page (domain.com/product):

[CODE REDACTED]

Any help would be appreciated! Thanks, /JJ

SOLUTION

Thanks for all the responses! This is what we ended up with:

[CODE REDACTED]

Massive thanks to Idan for helping me out in the WooCommerce Developer Slack channel!

CLEANER SOLUTION WITH REGISTRATION FORM REDIRECT FUNCTIONALITY

I was receiving some critical errors – Idan helped me create a cleaner script and implemented the registration form actions too!

// Hide Add to Cart for logged out users
add_action( 'init', 'creatorcabin_hide_price_add_cart_not_logged_in' );
function creatorcabin_hide_price_add_cart_not_logged_in() {   
   if ( ! is_user_logged_in() ) {      
      remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

// Add Login to Buy button for logged out users
add_action( 'woocommerce_single_product_summary', 'creatorcabin_user_logged_out_disable_add_to_cart', 30 );
function creatorcabin_user_logged_out_disable_add_to_cart() {
   if ( ! is_user_logged_in() ) {  
    $parameter = (is_singular("product")) ? '?product_page=1&my_page_id=' . get_the_ID() : '';
    echo '<div class="login-to-buy-box"><h4 style="color: #E67E22;">Login to buy!</h4><p style="color: black;">Login or Sign Up for free to unlock the buy button and gain access to your downloads! <a href="/learn/using-our-website/why-do-i-need-an-account-to-buy-stuff/" target="_blank><p style="font-style: italic;">Why do I need an account to buy stuff?</p></a><a href="/my-account' . $parameter . '"><div class="user-bought-singleproduct">Login / Register ></div></a></div>';
    }
}

// Referer
add_action( 'woocommerce_login_form_end', 'creatorcabin_actual_referer' );
function creatorcabin_actual_referer() {
   $product_page = (isset($_GET['product_page'])) ? $_GET['product_page'] : 0;
   $page_id = (isset($_GET['my_page_id'])) ? $_GET['my_page_id'] : 0;
   echo '<input type="hidden" name="product_page" value="' . $product_page . '" /><input type="hidden" name="my_page_id" value="' . $page_id . '" />';
}

//Login redirect
function custom_login_redirect($redirect) {
    if (isset($_POST['my_page_id']) && isset($_POST['product_page']) && intval($_POST['product_page']) === 1) {
        $redirect = get_permalink($_POST['my_page_id']);
    }
    return $redirect;
}
add_filter('woocommerce_login_redirect', 'custom_login_redirect', 10, 1);


// Action and Filter for Registration form
add_action( 'woocommerce_register_form_end', 'creatorcabin_actual_referer' );
add_filter('woocommerce_registration_redirect', 'custom_login_redirect', 10, 1);

Again, massive thanks to Idan for helping me out in the WooCommerce Developer/Community Slack channel!

3

Answers


  1. why don’t you just add a query arg to the link on product pages?

    edit:
    okay, so without going into too much detail as I’m tired and somewhat inebriated and can’t be trusted around semicolons right now:

    I would use https://developer.wordpress.org/reference/functions/wp_login_url/ to set up the hrefs for my login links. You’ll notice that the function comes with:
    a: an optional argument for passing the url that the user should be referred to after login
    and b: a filter hook called ‘login_url’ that you can use to hijack the process and apply your own logic in.

    also wordpress comes with a function conveniently called ‘add_query_arg’ which does exactly what it says on the tin. (https://developer.wordpress.org/reference/functions/add_query_arg/)

    so if i were to set up some php that would return that string on a product page I’d do something like this:

    $refer_to_url = get_permalink(get_the_ID()); //get current post/page permalink
    $refer_to_url = add_query_arg('is_product_page', true, $refer_to_url); //add arguments to that url.
    $this_login_url = wp_login_url($refer_to_url);
    

    then I’d probably try and set up a filter that would change the referring url to e.g. the user’s account page if is_product_page is not true.
    https://developer.wordpress.org/reference/functions/add_filter/

    you may also have to register the queryvar using

    add_filter( 'query_vars',  function ( $qvars ) {
        $qvars[] = 'is_product_page';          
        return $qvars;
    }); 
    

    otherwise wordpress might refuse to process the query var.

    hope that helps.

    Login or Signup to reply.
  2. You need to check on wp or template_redirect hook is previous page is shop page or not. I have assume and suggest code.

    redirect after login will redirect and second function will check is request uri contains shop or not.

    <?php
    
    // Function to redirect after login (best so far)
    function redirect_after_login(){
      global $wp;
     
          if (!is_user_logged_in() && !is_home() && ($wp->query_vars['pagename'] != 'downloads') ){
            $redirect = home_url() . "/wp/wp-login.php?redirect_to= $protocol://" . 
            $_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]);
    
    
            $shop_url = $_SERVER["REQUEST_URI"];
            $shop_end = "/shop/";
    
            if (!endsWith($shop_url, $shop_end)) {
    
                wp_redirect( $redirect );
                exit;
            }
         }
    
    }
    add_action( 'wp', 'redirect_after_login', 3 );
    
    // Check is previous page requst url shop page
    
    function isCheckShop($haystack, $needle) {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }
        return (substr($haystack, -$length) === $needle);
    }
    
    Login or Signup to reply.
  3. Actually,

    The wp_login_url() function let you specify a redirect variable through $redirect.

    <?php 
    
    // for the sake of the argument... 
    $current_url = home_url( '/product/spiderman-toy-statue-red' );
    
    // in live environment you could use something like this... 
    // global $wp;
    // $current_url = home_url( add_query_arg( $_GET, $wp->request ) );
    
    echo '<a href="' . esc_url( wp_login_url( $current_url )  ) . '">Login redirect example</a>';
    

    Your user would click that link on a product page and after login be redirected to that page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search