1

There is a following code in one of the installed plugins:

wp_enqueue_script( 'google-recaptcha',
    add_query_arg(
        array(
            'render' => $service->get_sitekey(),
        ),
        'https://www.google.com/recaptcha/api.js'
    ),
    array(),
    '3.0',
    true
);

This code produces the following URL for script downloading:

https://www.google.com/recaptcha/api.js?render=<sitekey>&ver=3.0

I need to inject a locale component into this URL to make it look like

https://www.google.com/recaptcha/api.js?hl=<locale>&render=<sitekey>&ver=3.0

I'm already wrote a function to get required locale part, but I don't know how to modify an URL for enqueued script (of course I don't want to touch the plugin source code). The only thing came to my mind is to look at the wp_scripts object and somehow modify it before the scripts enqueue task take place. Is there a better way to do this? Some hook I'm not aware of or something?

1 Answer 1

2

You can use the script_loader_src function to filter the URLs of scripts before they are output in a <script> tag. I'd suggest something like this:

add_filter(
    'script_loader_src',
    function( $src, $handle ) {
        // Only filter the specific script we want.
        if ( 'google-recaptcha' === $handle ) {
            // Add the argument to the exisitng URL.
            $src = add_query_arg( 'hl', '<locale>', $src );
        }

        // Return the filtered URL.
        return $src;
    },
    10, // Default priority.
    2 // IMPORTANT. Needs to match the number of accepted arguments.
);

Just replace '<locale>' with whichever locale you need, or a variable containing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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