How to Add Additional Attributes to the Script Tag in WordPress?

In

Often it is required to add some additional attributes to the script tag in WordPress. Since, we use wp_register_script to properly register scripts with WordPress but the function doesn’t give us the flexibility to pass additional attributes as parameters. So we need to find an alternative way to do this.

In this special episode of Useful WordPress Hooks and Filters, we are going to learn something very special and deep into the hooks ecosystem.

First, enqueue the script

Our site requires a third party script to enqueue to the page. Let’s enqueue the script for dropbox.


<?php
add_action( 'wp_enqueue_scripts', 'site_enqueue_scripts' );
function site_enqueue_scripts() {
  wp_enqueue_script(
    'site-script-dropbox',
    'https://www.dropbox.com/static/api/1/dropins.js',
    array(),
    '2.3',
    false
  );
}

But the fact is, we need to pass the attribute data-app-key="MY-APP-KEY" to the script tag. Since, WordPress doesn’t allow to add attributes to the script tag directly when enqueueing the scripts so we need to find the right action filter that help us to do the job.

Here comes our savior, the script_loader_tag action filter.

This filter allows us to modify the script tag that enqueues on the page.

The filter provides us 3 parameters to interact with. Let’s look at the code example below first.

<?php


add_filter('script_loader_tag','site_add_attr_to_script',10,3);
function site_add_attr_to_script( $tag, $handle, $src ){
    if ( 'site-script-dropbox' === $handle ) {
      $tag = '<script type="text/javascript" src="' . esc_url( $src ) . '" id="site-script-dropbox" data-app-key="MY_APP_KEY"></script>';
    }

  return $tag;
}

Since, all the scripts enqueues by passing through this filter so we need to be careful not to mess up with other scripts. We will only interact with the script that has handle site-script-dropbox as specified above when we enqueued the script.

If the script handle matches our condition, then we will modify the script $tag and set our attributes as necessary.

Thanks for reading!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *