1

I'm trying to show different language on front end based on page post meta setting. Mine problem is that I can see that locale is changed, but text still stays in English. Only if I change locale trough 'Settings > General' and set it to desired one, my translations load up and display correctly.

add_filter( 'locale', 'set_my_locale' );
function set_my_locale( $lang ) {

  if ( get_field('page_language', get_the_ID() ) ) {

    $lang = get_field('page_language', get_the_ID() );
  }

  return $lang;
}

function load_textdomain(){
  $domain = 'textdomain';

  load_theme_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain );
  load_theme_textdomain( $domain, get_stylesheet_directory() . '/lang' );
  load_theme_textdomain( $domain, get_template_directory() . '/lang' );
}
add_action( 'after_setup_theme', 'load_textdomain' );

If I try to print_r( get_locale() ); I can see that correct locale is set, but translations are not displayed, but instead I see original text.

If someone can point me please?

Should I use some different hook, or what I'm doing wrong?

0

Ok, I'v found out a way to do it with query_var. Looks like the problem was that locale was set to late in loading process.

If meta field/value exists redirect to page with ?lang=lang-attribute, and then set locale based on that.

function si_update_locale( $lang ) {

  if ( isset( $_GET['lang'] ) && ! empty( $_GET['lang'] ) ) {

    if( $_GET['lang'] == 'it' ) {
        $lang = 'it_IT';    
    }

  }
  return $lang;
}
add_filter( 'locale', 'si_update_locale' );


function si_load_textdomain(){

  $domain = 'textdomain';

  load_theme_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain );
  load_theme_textdomain( $domain, get_stylesheet_directory() . '/lang' );
  load_theme_textdomain( $domain, get_template_directory() . '/lang' );
}
add_action( 'after_setup_theme', 'si_load_textdomain' );


function si_set_locale() {
    $post_id = get_the_ID();
    $lang    = get_field('page_language', $post_id );

    if ( $lang && ! isset( $_GET['lang'] ) ) {

        switch ( $lang ) {

            case 'it_IT':

                wp_redirect( add_query_arg( array( 'lang' => 'it'), get_permalink(  $post_id ) ) );
                exit;

            break;
        }

  }
}
add_filter( 'template_redirect', 'si_set_locale' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.