Porcellino80
Porcellino80

Reputation: 447

Src file path with php (wordpress) in a javascript file

For some reason the normal src path of my template made with wordpress doesn't work. It is embedded in a javascript connect to my footer.php. Now my question is: is it possible to call an image with src inside a javascript with a php snippet? Here is my code so far:

var d = new Date();

document.getElementById("copyright").innerHTML = "&copy;" + " " + (d.getFullYear()) + " " + "All Rights Reserved" + " " + " " +"<img src='wp-content/themes/wpboot/images/maple.svg' alt='Canadian maple leaf' width='14'>" + " " + "We Are A Canadian Company";

I'm trying to add a php snippet like that:

<img src="<?php bloginfo('template_directory'); ?>/images/maple.svg" width="60" alt="Maple">

To achieve something like that:

document.getElementById("copyright").innerHTML = "&copy;" + " " + (d.getFullYear()) + " " + "All Rights Reserved" + " " + " " +"<img src='<?php bloginfo('template_directory'); ?>/images/maple.svg' alt='Canadian maple leaf' width='14'>" + " " + "We Are A Canadian Company";

I tried to build a var called:

var template = "<?php bloginfo('template_directory'); ?>/";

And I added to the src but I didn't work.. any clue?

Upvotes: 0

Views: 375

Answers (1)

Mansukh Khandhar
Mansukh Khandhar

Reputation: 2582

In .js file we can't used php so in WordPress get values as like this "myscript" to used your script "handler".

in your functions.php file

wp_enqueue_script('myscript',get_template_directory_uri().'/js/myscript.js',array('jquery'));
wp_localize_script( 'myscript', 'mycustomurl',  get_template_directory_uri() );

in js file use as like this alert just your info.

alert(mycustomurl);
document.getElementById("copyright").innerHTML = "&copy;" + " " + (d.getFullYear()) + " " + "All Rights Reserved" + " " + " " +"<img src='"+mycustomurl+"/images/maple.svg' alt='Canadian maple leaf' width='14'>" + " " + "We Are A Canadian Company";

Upvotes: 1

Related Questions