Use WP Site Theme url in Javascript

To use wordpress Site URL, Theme Url or any information that you are fetching using wordpress default function and want to use it in Javascript that is either Internal or external.

If javascript code used in internal .php file than you can directly call wp function using <?php ?> in Javascript but main confusion is what is the best way while want to use in External .js file because we cant use Php script in External .js file.

In this case  2 possible solution.
1 Declare JS variable in header.php and assign value it
2 use WP wp_localize_script function : Localizes a registered script with data for a JavaScript variable. more

Example :
<?php 
wp_localize_script( 'custom-js', 'wpcj_variable', array( 'template_url' => get_bloginfo('template_url'),   'site_url' => get_bloginfo('url')));
?>
To use in Javascript
<script>
alert(wpcj_variable.template_url);
alert(wpcj_variable.site_url);
</script>


Post a Comment

0 Comments