I need to include the path to my theme file within a javascript file. How would I go about this? I have already tried:
var templateUrl = "<?php get_stylesheet_directory_uri(); ?>";
function LightboxOptions() {
this.fileLoadingImage = "'"+templateUrl+"/img/loading.gif'";
this.fileCloseImage = "'"+templateUrl+"/img/close.png'";
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
This does not give me the path, but just inserts <?php get_stylesheet_directory_uri(); ?>
instead of the actual path. Any ideas? Thanks in advance!
What you’re looking for is wp_localize_script function.
You use it like this when enqueing script
wp_register_script( 'my-script', 'myscript_url' );
wp_enqueue_script( 'my-script' );
$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
//after wp_enqueue_script
wp_localize_script( 'my-script', 'object_name', $translation_array );
In your style.js, there is going to be:
var templateUrl = object_name.templateUrl;
...