Search code examples
phpjquerywordpressattr

Using wp_localize_script image path in jQuery attr


This is my PHP code to load my jQuery and my image using wp_localize_script in a WordPress child theme.

$image = sprintf( '%s/image.png', get_stylesheet_directory_uri() );    
wp_localize_script( 'scroll-image', 'Image', $image ) ) ) );

And this is my jQuery

 $( '.div img' ).attr( 'src', 'Image' );

But the HTML output returns the 2nd parameter for wp_localize_script without the full path to the image.

<img src="Image">

What have i missed?

Why do i need to include the full path to the image in the jQuery when it is already included in the PHP for the $image variable?

I did check this answer but i don't see why it has to be done this way because the image tag is already output using other PHP code. All i'm trying to do is replace the image src URL.

Update : How about if i want to use the image as a option like this

wp_localize_script( 'scroll-image', 'Image', array( 'src' => str_replace( 'http:', '', get_option( 'my-image' ) ) ) );

Solution

  • wp_localize_script takes three arguments.

    • $handle: Script handle the data will be attached to.
    • $object_name: which is the variable that will be accessed in your javascript file.
    • $data: an array of data to pass to the object

    In your jQuery code you are accessing Image as a string not a variable.

    Your JS code need to change to this:

     $( '.div img' ).attr( 'src', obj_name.image );
    

    And your PHP code should look like this:

    $image = sprintf('%s/image.png', get_stylesheet_directory_uri());
    wp_localize_script('scroll-image', 'obj_name', array(
        "image" => $image
    ));