I need to insert something like this in wordpress:

<script id="customID" data-name="customDataName" src="https://url.com/main.js"></script>    

I am using wp_enqueue_script but I can not find how to add an id and a data-name to the script

  • You can't add attributes directly with wp_enqueue_script(). There's workarounds, but could you elaborate on what you're trying to achieve, it could influence the answer. – Jacob Peattie Feb 2 '18 at 12:40
  • Thanks for you answer. The script main.js gets the data-name to open a chat window custom for that data-name. I was using add_action('wp_footer', 'myScript',50); but I see that it is not the proper way to use it. – Iván Tammaro Feb 2 '18 at 12:47
  • Is the script itself yours, or a 3rd party's? – Jacob Peattie Feb 2 '18 at 12:48
  • It is mine, but is being used in other places already. I'm getting data-name using the id var dataName=document.getElementById(id).getAttribute("data-name"); – Iván Tammaro Feb 2 '18 at 12:53

script_loader_tag filter was introduced in WordPress 4.1:

add_filter( 'script_loader_tag', 'my_script_attributes', 10, 3 );

function my_script_attributes( $tag, $handle, $src )
    // change to the registered script handle, e. g. 'jquery'
    if ( 'MY_SCRIPT_HANDLE' === $handle ) {

        // add attributes of your choice
        $tag = '<script id="customID" data-name="customDataName" src="' . esc_url( $src ) . '"></script>';

    return $tag;
|improve this answer|||||

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.