Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.6 kB
11
Indexable
<?php
// Add this code to your theme's functions.php or a custom plugin

// Handle login redirect
function custom_login_redirect($redirect, $user) {
    // Check if there's a redirect parameter
    if (isset($_GET['redirect'])) {
        $redirect_url = esc_url_raw($_GET['redirect']);
        
        // Verify this is a valid internal URL
        $site_url = parse_url(get_site_url(), PHP_URL_HOST);
        $redirect_host = parse_url($redirect_url, PHP_URL_HOST);
        
        // Only allow redirects to the same domain for security
        if ($redirect_host === $site_url) {
            return $redirect_url;
        }
    }
    
    // Return default redirect if no custom redirect is set
    return $redirect;
}
add_filter('woocommerce_login_redirect', 'custom_login_redirect', 10, 2);

// Handle redirect for already logged-in users
function check_login_redirect() {
    // Only run on frontend
    if (is_admin()) {
        return;
    }
    
    // Check if user is logged in and redirect parameter exists
    if (is_user_logged_in() && isset($_GET['redirect'])) {
        $redirect_url = esc_url_raw($_GET['redirect']);
        
        // Verify this is a valid internal URL
        $site_url = parse_url(get_site_url(), PHP_URL_HOST);
        $redirect_host = parse_url($redirect_url, PHP_URL_HOST);
        
        // Only redirect to same domain for security
        if ($redirect_host === $site_url) {
            wp_redirect($redirect_url);
            exit;
        }
    }
}
add_action('template_redirect', 'check_login_redirect');
Leave a Comment