admin管理员组

文章数量:1302895

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

wp_enqueue_script( 'google-recaptcha',
    add_query_arg(
        array(
            'render' => $service->get_sitekey(),
        ),
        '.js'
    ),
    array(),
    '3.0',
    true
);

This code produces the following URL for script downloading:

.js?render=<sitekey>&ver=3.0

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

.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?

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/recaptcha/api.js'
    ),
    array(),
    '3.0',
    true
);

This code produces the following URL for script downloading:

https://www.google/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/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?

Share Improve this question asked Feb 18, 2021 at 8:06 Ivan ShatskyIvan Shatsky 8901 gold badge7 silver badges12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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.

本文标签: Modifying an enqueued script URL