I am using a slider to show my images that works fine on my sit but when I converted my site in to a wordpress theme it started giving me troubles on loading the images, slider is active but images are not showing, I tried using wp_localize_script with no luck, I am probably making some mistake please check my code and let me know what it is that I am doing wrong!
Here is my code:
functions.php
// I took this code snippet from another stackexchange answer!
function wpa_scripts() {
wp_enqueue_script(
'wpa_script',
get_template_directory_uri() . '/js/custom.js',
array('jquery'),
false,
true
);
$script_data = array(
'image_path' => get_template_directory_uri() . '/images/'
);
wp_localize_script(
'wpa_script',
'wpa_data',
$script_data
);
}
add_action( 'wp_enqueue_scripts', 'wpa_scripts' );
And here is my custom.js file:
$(function(){
jQuery(document).ready(function() {
$('#home').backstretch([
image_path+"home-bg-slideshow1.jpg",
image_path+"home-bg-slideshow2.jpg",
image_path+"home-bg-slideshow3.jpg",
], {duration: 2000, fade: 750});
});
})
Any idea how to fix this? its my first time messing with the wp_localize_script
I am using a slider to show my images that works fine on my sit but when I converted my site in to a wordpress theme it started giving me troubles on loading the images, slider is active but images are not showing, I tried using wp_localize_script with no luck, I am probably making some mistake please check my code and let me know what it is that I am doing wrong!
Here is my code:
functions.php
// I took this code snippet from another stackexchange answer!
function wpa_scripts() {
wp_enqueue_script(
'wpa_script',
get_template_directory_uri() . '/js/custom.js',
array('jquery'),
false,
true
);
$script_data = array(
'image_path' => get_template_directory_uri() . '/images/'
);
wp_localize_script(
'wpa_script',
'wpa_data',
$script_data
);
}
add_action( 'wp_enqueue_scripts', 'wpa_scripts' );
And here is my custom.js file:
$(function(){
jQuery(document).ready(function() {
$('#home').backstretch([
image_path+"home-bg-slideshow1.jpg",
image_path+"home-bg-slideshow2.jpg",
image_path+"home-bg-slideshow3.jpg",
], {duration: 2000, fade: 750});
});
})
Any idea how to fix this? its my first time messing with the wp_localize_script
Share Improve this question asked May 19, 2019 at 13:26 FSKFSK 31 bronze badge1 Answer
Reset to default 0You're not accessing the value correctly. The 2nd argument of wp_localize_script
is the name of a JavaScript object that your data will be added to. In your case it's wpa_data
. This means that the image_path
is accessed at wpa_data.image_path
:
$(function(){
jQuery(document).ready(function() {
$('#home').backstretch([
wpa_data.image_path+"home-bg-slideshow1.jpg",
wpa_data.image_path+"home-bg-slideshow2.jpg",
wpa_data.image_path+"home-bg-slideshow3.jpg",
], {duration: 2000, fade: 750});
});
})