Custom data-id wp_enqueue_script

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

1 Answer
1

script_loader_tag filter was introduced in WordPress 4.1:

<?php
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;
}

Leave a Comment