0

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

0

You'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});
    });
  })
|improve this answer|||||
  • Brother I tried this too before and now again but its somehow not working! – FSK May 19 '19 at 13:50
  • What exactly isn't working? What debugging have you done? Does the slideshow work but the images are blank? Does the slideshow work at all? Are there errors in the console? What is the URL for images when you inspect the source? – Jacob Peattie May 19 '19 at 13:52
  • Slider is loading but images are blank and the URL source is empty when I inspect, console however is showing this error: Uncaught TypeError: $ is not a function at custom.js?ver=5.0.4:6 – FSK May 19 '19 at 14:00
  • @FSK The cause is probably the noConflict mode. Try to wrap your code like this:: jQuery(document).ready(function($) { $('#home').backstretch( /* ...yout code... */ ); }); – nmr May 19 '19 at 14:57
  • Yes I tried and it worked thanks allot! – FSK May 20 '19 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.