How can the plugin directory path be returned into <script> </script> instead of hard coding the path?

Here is the custom-page.php:

<?php get_header(); ?>

<script type="text/javascript" src="http://local.wordpress.test/wp-content/plugins/path-to-file/script.js"></script>

<?php get_footer(); ?>
  • 1
    Is your question about the script (javascript.js)? Then use wp_enqueue_script(). Is it about using the path as a variable within JavaScript? Then wp_localize_script() is your friend
    – kero
    Commented Nov 23, 2018 at 14:58

4 Answers 4


Take a look at this: https://wordpress.stackexchange.com/a/119084/121955

plugins_url( "path/to/file", __FILE__ );


<script src="<?php echo plugins_url( "path/to/file", __FILE__ ); ?>"></script>
  • How would this be applied within the <script> </script> tags?
    – 65535
    Commented Nov 23, 2018 at 15:36
  • Added an example Commented Nov 23, 2018 at 15:37

To make the plugin url available in javascript:

  *register the javascript
  wp_register_script( 'some_handle', plugins_url( "plugin-name/path-to-file/script.js") );

  *localize the plugin url.
  *someObjectName.pluginsUrl then can be used to return
  *the plugin url to the javascript
  wp_localize_script('some_handle', 'someObjectName', array(
      'pluginsUrl' => plugins_url( "plugin-name/path-to-file/script.js"),

From Javascript the plugin url can be returned in the following way:

<script type="text/javascript">
     var url = someObjectName.pluginsUrl;
     alert( url );

Here is an example from one of my plugins I developed.

    function insert_scripts()
    wp_enqueue_script('jquery', '<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>', '1.0.0', true);

    wp_enqueue_script( 'test1', plugin_dir_url( __FILE__ ) . 'js/test1.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'test2', plugin_dir_url( __FILE__ ) . 'js/test2.js', array('jquery'), '1.0.0', true );

add_action( 'wp_enqueue_scripts', 'xwp_insert_scripts' );

As per the code above, the scripts should load into the head. However, if modification have been made they could load else where. This funtion will need to be added to a functions.php file. NOTE: if you add this to the core theme functions.php file it will be modified upon update. Best bet is to create a child theme and use a custom functions.php file.

<script type="text/javascript" src="<?php echo plugins_url( "plugin-name/path-to-file/script.js"); ?>"></script>

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.