1

I'm converting my static Html website into wordpress and some images don't show. This is because I use Jquery to change the "src" of my image. now in my index.php I added bloginfo('template_url') in every image src. My problem is I don't know how to call it in Jquery.

In my php code it looks like this

  <img src="<?php bloginfo('template_url'); ?>/images/logo-dark.png">

and

in my JS code I access it like this

$("img").attr("src","images/logo-light.png");

How do I call the in JQuery? TYIA

1
  • Try $("img").attr("src","<?php bloginfo('template_url'); ?>images/logo-light.png"); Commented Jan 29, 2019 at 6:30

4 Answers 4

1
$("img").attr("src","<?php bloginfo('template_url') ?>images/logo-light.png")
Sign up to request clarification or add additional context in comments.

Comments

0

You can use wp_localize_script which allows you to access php data in JavaScript file.

First register your script using wp_enqueue_script

wp_enqueue_script( 'theme_script', get_template_directory_uri() . '/assets/js/code.js', array( 'jquery' ), '', true );

Then register your php variables to the code.js file.

$phpData = array(
    'logo_dark' => get_template_directory_uri()."/images/logo-dark.png",
);
wp_localize_script( 'theme_script', 'themeObj', $phpData );

Here

  1. theme_script is the name of your javascript WordPress handle which we used on wp_enqueue_script.
  2. themeObj is the name of JavaScript variable which we will use to access to our php data from JavaScript file.
  3. $phpData is an array of the data we wish to serve.

Now can access the logo_dark value using themeObj.logo_dark from your JS file.

$("img").attr("src", themeObj.logo_dark);

For more info, check wordpress codex

Comments

0

This may do this :

$("img").attr("src","<?php bloginfo('template_url'); ?>/images/logo-light.png");

1 Comment

It displays <?php bloginfo('template_url'); ?> as a text
0

If you want to use your php function in jQuery block in your .php file then you can use the code which @vaibhav and @elraphty pointed out

$("img").attr("src","<?php bloginfo('template_url'); ?>/images/logo-light.png");

And if you want to use it in .js file then you need to assign a variable in head tag

<script>
   var baseImgurl =  '<?php bloginfo('template_url'); ?>';
</script>

and then use it in .js file

$("img").attr("src",baseImgurl+"/images/logo-light.png");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.