I have made a bit of progress now. But stuck. I have described the problem in the code below:
add_action('init', 'my_init');
function my_init()
{
global $polylang;
if (!session_id())
{
session_start();
}
if (!empty($_REQUEST['lang']) && !is_numeric($_REQUEST['lang']))
{
// Redirect to new lang url
if (!empty($_SESSION['theme_func_lang']) && $_SESSION['theme_func_lang'] != $_REQUEST['lang'])
{
// PROBLEM: This executes even in admin and returns error cause
// $polylang->choose_lang object doesn't exist there.
// But even if I remove this code, ans switch language from
// admin, add this code again and try to update frontend,
// frontend won't update to the new language.
$lang = $polylang->model->get_language($_SESSION['theme_func_lang']);
$polylang->choose_lang->curlang = $lang->curlang;
do_action('pll_language_defined', $lang->curlang->slug, $lang->curlang);
unset($_SESSION['theme_func_lang']);
$polylang->choose_lang->home_requested();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}
else
{
$lang = $polylang->model->get_language($_REQUEST['lang']);
$polylang->curlang = $lang;
// Update frontend lang
if (!headers_sent() && PLL_COOKIE !== false && (!isset($_COOKIE[PLL_COOKIE]) || $_COOKIE[PLL_COOKIE] != $lang->slug))
{
setcookie(
PLL_COOKIE,
$lang->slug,
time() + 31536000 /* 1 year */,
COOKIEPATH,
2 == $polylang->options['force_lang'] ? parse_url($polylang->links_model->home, PHP_URL_HOST) : COOKIE_DOMAIN
);
}
// Update admin lang
if (!defined('DOING_AJAX') && current_user_can('edit_user', $user_id = get_current_user_id()))
{
update_user_meta($user_id, 'pll_filter_content', $lang);
$polylang->pref_lang = $lang;
}
// Flag new lang
$_SESSION['theme_func_lang'] = $lang->slug;
}
}
}