Get WordPress theme directory from Javascript file

2022/06/19 23:03

As you know, it’s very easy to use the get_template_directory_uri() function to get the directory of theme folder in WordPress. But if you are trying to get the WordPress directory from Javascript file, it needs special method.  Let me show you how to do it easily with just two lines of code.

You need to first register the JS file with wp_register_script() function and use another function wp_localize_script() to assign the value to an variable.

wp_enqueue_script('payment-handler', plugin_dir_url(__FILE__) . 'assets/js/payment-handler.js');
wp_localize_script('payment-handler', 'pluginPath', array('pluginURL' => plugin_dir_url( __FILE__ ),));

In your Javascript file, you can use the theme path value like this way.

var plugin_Url= pluginPath.pluginURL;

Leave a Reply

Back to top