I've been searching for plugins and snippets which would handle it for hours, but no success. Every single answer doesn't work for me. I have "Log in" link in menu, leading to WooCommerce "My account" page, which shows login form. I want customers to return to page where "Log in" link was clicked after successful login.
wp_get_referer() doesn't return anything and $_SERVER["HTTP_REFERER"] returns my account page if put within function hooked to woocommerce_login_redirect (I used PHP debug console to check).
Here is my code:
// Redirect user after login.
add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
function wc_custom_user_redirect( $redirect, $user ) {
// Get the first of all the roles assigned to the user
$role = $user->roles[0];
$dashboard = admin_url();
if (in_array($role, array('administrator', 'shop_manager', 'editor', 'author', 'contributor'))) {
$redirect = $dashboard;
} elseif (in_array($role, array('customer', 'subscriber'))) {
$redirect = $_SERVER["HTTP_REFERER"];
} else {
$redirect = $_SERVER["HTTP_REFERER"];
}
return $redirect;
}
Here is where filter which I used appears in WooCommerce code:
/**
* Process the login form.
*/
public static function process_login() {
$nonce_value = isset( $_POST['_wpnonce'] ) ? $_POST['_wpnonce'] : '';
$nonce_value = isset( $_POST['woocommerce-login-nonce'] ) ? $_POST['woocommerce-login-nonce'] : $nonce_value;
if ( ! empty( $_POST['login'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-login' ) ) {
try {
$creds = array(
'user_password' => $_POST['password'],
'remember' => isset( $_POST['rememberme'] ),
);
$username = trim( $_POST['username'] );
$validation_error = new WP_Error();
$validation_error = apply_filters( 'woocommerce_process_login_errors', $validation_error, $_POST['username'], $_POST['password'] );
if ( $validation_error->get_error_code() ) {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . $validation_error->get_error_message() );
}
if ( empty( $username ) ) {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'Username is required.', 'woocommerce' ) );
}
if ( is_email( $username ) && apply_filters( 'woocommerce_get_username_from_email', true ) ) {
$user = get_user_by( 'email', $username );
if ( isset( $user->user_login ) ) {
$creds['user_login'] = $user->user_login;
} else {
throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . __( 'A user could not be found with this email address.', 'woocommerce' ) );
}
} else {
$creds['user_login'] = $username;
}
// On multisite, ensure user exists on current site, if not add them before allowing login.
if ( is_multisite() ) {
$user_data = get_user_by( 'login', $username );
if ( $user_data && ! is_user_member_of_blog( $user_data->ID, get_current_blog_id() ) ) {
add_user_to_blog( get_current_blog_id(), $user_data->ID, 'customer' );
}
}
// Perform the login
$user = wp_signon( apply_filters( 'woocommerce_login_credentials', $creds ), is_ssl() );
if ( is_wp_error( $user ) ) {
$message = $user->get_error_message();
$message = str_replace( '<strong>' . esc_html( $creds['user_login'] ) . '</strong>', '<strong>' . esc_html( $username ) . '</strong>', $message );
throw new Exception( $message );
} else {
if ( ! empty( $_POST['redirect'] ) ) {
$redirect = $_POST['redirect'];
} elseif ( wp_get_referer() ) {
$redirect = wp_get_referer();
} else {
$redirect = wc_get_page_permalink( 'myaccount' );
}
wp_redirect( apply_filters( 'woocommerce_login_redirect', $redirect, $user ) );
exit;
}
} catch ( Exception $e ) {
wc_add_notice( apply_filters( 'login_errors', $e->getMessage() ), 'error' );
do_action( 'woocommerce_login_failed' );
}
}
}
I tried the answer of #dineshkashera but it throws an error as starting a session is not a good practice and also wp_get_referer hook is not working and thus $_SERVER['HTTP_REFERER'].
So my only solution is creating a cookie that will save our previous link.
Here's my Code:
//First we need to set a cookie that will save the previous url
setcookie('nlcrc', $_SERVER['HTTP_REFERER'], time() + 86000, COOKIEPATH, COOKIE_DOMAIN, false);
//Then initiate Woocommerce redirect hook
//This is for the WC login redirect
add_filter('woocommerce_login_redirect', 'wcc_redirects', 9999, 2);
//I have added also WC registration redirect
add_filter('woocommerce_registration_redirect', 'wcc_redirects', 9999, 1);
//Then this will be the handler
function wcc_redirects ($redirect) {
if (isset($_COOKIE['nlcrc'])) {
$redirect = $_COOKIE['nlcrc'];
return $redirect;
} else {
$redirect = home_url();
return $redirect;
}
}
or you can also somewhat quick and dirty with Javascript. If your default login page is Woocommerce My Account Page.
add_filter('woocommerce_login_redirect', 'wc_cstm_login_redirect', 99 );
function wc_cstm_login_redirect () {
echo "<script type='text/javascript'>
history.go(-2);
</script>";
}
Please try the below code, i hope it helps you.
Paste the below code in current active theme functions.php file.
// start global session for saving the referer url
function start_session() {
if(!session_id()) {
session_start();
}
}
add_action('init', 'start_session', 1);
// get referer url and save it
function redirect_url() {
if (! is_user_logged_in()) {
$_SESSION['referer_url'] = wp_get_referer();
} else {
session_destroy();
}
}
add_action( 'template_redirect', 'redirect_url' );
//login redirect
function login_redirect() {
if (isset($_SESSION['referer_url'])) {
wp_redirect($_SESSION['referer_url']);
} else {
wp_redirect(home_url());
}
}
add_filter('woocommerce_login_redirect', 'login_redirect', 1100, 2);
We have to use WordPress referrer function:
For example, set referrer URL in session or hidden field by clicking on add to cart button or any button to store previous URL. Once login or register success add WooCommerce success login redirect to that URL.
Read about the Referrer function.
Here's an answer about the WooCommerce login redirect.
this will solve your prolem
add_filter( 'woocommerce_login_redirect', function(){
wp_safe_redirect(wp_get_referer());
}, 10, 2 );
Need to set a login control on a button for my wp website. Button's code appears to be like this:
$enable_redirect = get_field('redirect_to_offer') ? get_field('redirect_to_offer') : array('');
echo'' . fw_ssd_get_option('show-code-text') . '';
}
My goal is to check if the user who clicks on that button is logged in or not with:
if ( function_exists('um_profile_id') && !um_profile_id() && get_field('registered_members_only') ) {
wp_redirect(home_url('login/'));
exit;
}
But I couldn't figure out where should I put the controller code. F1 please.
Since your button URL is external, changing the button URL from the beginning seems to be a better option (as discussed on the comments):
$enable_redirect = get_field( 'redirect_to_offer' ) ? get_field('redirect_to_offer') : array( '' );
if ( function_exists( 'um_profile_id' ) && ! um_profile_id() && get_field( 'registered_members_only' ) ) {
$button_url = home_url( 'login/' );
} else {
$button_url = get_field( 'url' );
}
echo sprintf( '%4$s'
esc_url( $button_url ),
esc_attr( get_field( 'coupon_code' ) ),
esc_attr( $enable_redirect[0] ),
fw_ssd_get_option( 'show-code-text' )
);
The login status defines the final button URL.
Note: I used placeholder replacement with sprintf() in other to make it easier to read.
I'm very inexperienced with coding, so to anyone who bears with me a huge thank you in advance!
Here's what I'm trying to do: I want to make my website - that's currently displaying a logo that I've picked - display randomly one of the images that I've uploaded as the logo every time the page reloads.
Now this would be relatively easy if the theme was coded with a header - but for logos I can't find a plugin that does that and also can't manage to add this feature from inside the theme.
This is how the wordpress theme of my website calls for a logo:
<?php
if( $show_logo && has_custom_logo() ) {
the_custom_logo();
Here's the the_custom_logo() functions code:
function the_custom_logo( $blog_id = 0 ) {
echo get_custom_logo( $blog_id );
}
Now my thought for a solution was the following: I change the way wordpress returns an image through get_custom_logo() (I'm prepared to code that in every time there's a WP update).
Here's the functions code:
function get_custom_logo( $blog_id = 0 ) {
$html = '';
$switched_blog = false;
if ( is_multisite() && ! empty( $blog_id ) && (int) $blog_id !== get_current_blog_id() ) {
switch_to_blog( $blog_id );
$switched_blog = true;
}
$custom_logo_id = get_theme_mod( 'custom_logo' );
// We have a logo. Logo is go.
if ( $custom_logo_id ) {
$html = sprintf( '%2$s',
esc_url( home_url( '/' ) ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',
'itemprop' => 'logo',
) )
);
}
// If no logo is set but we're in the Customizer, leave a placeholder (needed for the live preview).
elseif ( is_customize_preview() ) {
$html = sprintf( '<img class="custom-logo"/>',
esc_url( home_url( '/' ) )
);
}
if ( $switched_blog ) {
restore_current_blog();
}
return apply_filters( 'get_custom_logo', $html, $blog_id );
}
Am I wrong in thinking that if I change $custom_logo_id = get_theme_mod( 'custom_logo' ); to acquire a random image out of my logo folder that it's gonna work? And if I'm not wrong, can anybody help me with how to write that piece of code?
I apologise if this is a dumb question. Have a great week!
this is the code which I'm trying
function search_url_rewrite() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
global $opt; if($opt['rewrite_slug_search']){ $search_url = $opt['rewrite_slug_search'];
} else { $search_url = 'search'; }
wp_redirect( home_url( $search_url ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'search_url_rewrite' );
the $search_url is option from my theme settings panel but there is a problem with the slash when I type test in search box I get searchtest instead of search/test do you have any idea how to get a slash between?
Is possible change this url
www.12345.com/?s=&cp_state=city
to this?
www.12345.com/city
Already try with htaccess but in wordpress it doesen't work
Hi have this code. Is possible change it to have a url like this www.12345.com/city?
add_action('template_redirect', 'search_url_rewrite_rule');
function search_url_rewrite_rule() {
global $wp_rewrite;
if ( is_search() && isset( $_GET['s'] ) ) {
$s = str_replace( array( ' ', '%20' ), '+', get_query_var( 's' ) );
wp_redirect( home_url( $wp_rewrite->search_base . '/' . remove_accents ( $s ) ) );
exit();
}
}
add_action('init','change_search_permalinks');
function change_search_permalinks( ) {
global $wp_rewrite;
$wp_rewrite->search_base = 'search';
}
Thank you in advance
In php level it is not good idea
You can use url shortlink in admin area of wordpress.