1

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 Nov 23 '18 at 14:58
2

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

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

EDITED:

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

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 );
 </script>
0

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.

0
<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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.