• Resolved leandro_S

    (@leandro_s)


    Hello everyone!

    I’m trying to get the user language inside the functions.php file in order to load some translations. The problem is that get_locale seems to be empty inside functions.php
    This is what I have in my functions file:

    $locale = get_locale();
    $lang = substr($locale, 0, 2);
    wp_enqueue_script('validate_languages', get_stylesheet_directory_uri() . '/js/localization/messages_'.$lang.'.js', array( 'jquery' ));

    This is the error I see in the console:

    GET https://www.mydomain.com/wp-content/themes/twentyfifteen_child/js/localization/messages_.js?ver=4.4.1

    I have also tried to use $locale alone (just in case native substr() funtion was not working), but I get the same error.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    I cannot replicate the problem on my installation, I suspect one of your plugins is improperly filtering ‘locale’. I get messages_en.js with your code.

    Incidentally, you should call wp_enqueue_script() from an action callback hooked to ‘wp_enqueue_scripts’.

    Thread Starter leandro_S

    (@leandro_s)

    Hello bcworkz!
    I have deactivated all my plugins and I’m still getting this error.
    I have another call to get_locale in the header.php and it works, is just this one in the functions.php which doesn’t return anything at all.
    Does this fact tell you something about the problem?

    Regarding the ‘wp_enqueue_scripts’ I have a function called ‘add_scripts’ with all the enqueues for scripts and styles, and after that I have the following line:

    add_action('wp_enqueue_scripts', 'add_scripts')

    Thanks in advance for your help!

    Thread Starter leandro_S

    (@leandro_s)

    How my code looks like now:

    $locale = get_locale();
    $lang = substr($locale, 0, 2);
    function add_scripts($lang)
    {
       wp_enqueue_script('validate_languages', get_stylesheet_directory_uri() . '/js/localization/messages_'.$lang.'.js', array( 'jquery' ));
    }
    add_action('wp_enqueue_scripts', 'add_scripts', $lang, 1);

    I’m I passing the $lang argument wrongly??

    Moderator bcworkz

    (@bcworkz)

    Yes, you cannot pass your own variables to action callbacks, what is passed is determined by the do_action() call and the fourth parameter of add_action(). The third parameter of add_action() is a priority value, it’s not passed to your callback.

    Put the get_locale() and substr() calls inside your callback along with wp_enqueue_script(), it’ll work fine there. The action fires in your <head> section, where you’ve already confirmed get_locale() works ??

    Thread Starter leandro_S

    (@leandro_s)

    Working!
    Thanks a lot bcworkz!!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘get_locale is empty when called inside functions.php’ is closed to new replies.