I want to setcookie if is_page(‘arabic’) or is_page(‘english’) then redirect to home_url()
only if the page name/slug arabic
or english
, I think that init action happen before the code determine the current page, how to do that
Also after fixing that problem , how can I be sure that setcookie will happen before the redirect so the cookie which Has just set will be shown (because cookie needs refresh)
Below is my code
function site_set_user_language() {
if(!isset($_COOKIE['site_language'])){
setcookie('site_language', 'ar', time()+3600*24*365*3,'/','.site.com');
}elseif(is_page('arabic') || is_page('english')){
if($_COOKIE['site_language'] == 'en'){
setcookie('site_language', 'ar', time()+3600*24*365*3,'/','.site.com');
wp_redirect( home_url());
exit();
}elseif($_COOKIE['site_language'] == 'ar'){
setcookie('site_language', 'en', time()+3600*24*365*3,'/','.site.com');
wp_redirect( home_url());
exit();
}
}
}
add_action( 'init', 'site_set_user_language',10,1);
add_action( 'template_redirect', 'site_lang_home_redirect' );
template_redirect
andwp
(as the OP noted in comments) are good hooks to do this. But there’s a problem of logic in the sample code. I think it should be like:There’s another problem, it would be better to go back to the original page when we click on the links Arabic and English:
home_url()
should besite_url($last_url)
. See this post, by Konstantin Kovshenin.For this, at each page, the link for those pages should be
http://example.com/LANGUAGE/?original_url=$last_url
. But that’s a topic for another Question*
.*
I’ve played with the concept and did this plugin.Finally I did it, I sent my question after more than a week trying to solve that problem, and it works finally just after 20 minets of sending my question 🙂 I needed to wait 8 hours because I was new to wordpress.stackexchange
So as I mentioned in the comment of my question, The solving ideas were to:
1- Use
wp
instead ofinit
to make the is_page do its effect.2- separate the redirect code from the cookie function
So the working code is:
and the redirect function: