template_redirect
and wp
(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:
add_action( 'template_redirect', 'cookie_redirect_wpse_113662' );
function cookie_redirect_wpse_113662() {
# No cookie set, let's do it
if( !isset( $_COOKIE['site_language'] ) )
set_cookie_wpse_113662( 'ar' );
# One of our pages, check/change cookie and redirect
if( is_page( array( 'arabic', 'english' ) ) )
{
# Page is Arabic and cookie was English, change cookie
if( is_page( 'arabic' ) && $_COOKIE['site_language'] == 'en' )
set_cookie_wpse_113662( 'ar' );
# Page is English and cookie was Arabic, change cookie
elseif( is_page( 'english' ) && $_COOKIE['site_language'] == 'ar' )
set_cookie_wpse_113662( 'en' );
# Redirect
do_redirect_wpse_113662();
}
});
function set_cookie_wpse_113662( $lingo ) {
setcookie( 'site_language', $lingo, time() + 3600 * 24 * 365 * 3, "https://wordpress.stackexchange.com/", '.example.com' );
}
function do_redirect_wpse_113662( $where="" ) {
$where = empty( $where ) ? home_url() : $where;
wp_redirect( $where );
exit();
}
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 be site_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.