首页 > 解决方案 > 在哪里使用 switch_to_locale() WordPress 功能?

问题描述

我已经制作了一个表格以使用switch_to_locale()功能切换语言

表格提交给admin_url('admin-post.php')

然后我处理它:


add_action('admin_post_change_lang_action', 'switch_site_language');
add_action('admin_post_nopriv_change_lang_action', 'switch_site_language');

function switch_site_language(){
    
    if(isset($_POST['_change_lang_nonce']) && wp_verify_nonce($_POST['_change_lang_nonce'], 
                                       'change_lang_action', false) && isset($_POST['lang'])) {
       
         switch_to_locale($_POST['lang']);

    }

    wp_safe_redirect(wp_get_referer());
}


但是当我只运行 switch_to_locale('ru_RU'); 时它不起作用 从外面它可以工作

这里有什么问题吗

提前致谢。

标签: phpwordpress

解决方案


我实际上找不到原因,但我找到了解决这个问题的好方法

我像这样提交了表格

  <form action="" method="GET">...</form>

对于处理程序:


add_action( 'wp_loaded', function () {

    if(isset($_GET['_change_lang_nonce']) && isset($_GET['lang'])){
        
        if(wp_verify_nonce($_GET['_change_lang_nonce'], 'change_lang_action', false)) {
        
            if(switch_to_locale( $_GET['lang'] )){
                wc_add_notice(__('Language changed with success'), 'success' );
            }else{
                wc_add_notice(__( 'Some thing Went Wrong please try later!'), 'error' );
            }

        }else{
            wc_add_notice(__( 'Some thing Went Wrong please try later!'), 'error' );
        }

        wp_safe_redirect(wp_get_referer());
    }
});


推荐阅读