WordPress path url in js script file WordPress path url in js script file wordpress wordpress

WordPress path url in js script file


According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">    var url = WPURLS.siteurl;</script>


You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head() is called, holding the template URL. Like:

<script type="text/javascript">var templateUrl = '<?= get_bloginfo("template_url"); ?>';</script>

And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):

Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";


    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);    wp_enqueue_script('custom-js');    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);