Support » Fixing WordPress » referencing my site path in jquery

  • pepperstreetuk


    I think this is going to be very simple for someone but I can’t seem to get to grips with it.
    I have a script (don’t comment on the code I am struggling as it is!)


    var mylogoimage = jQuery(“#logoid”).attr(‘src’);
    var templateUrl = (“”);

    jQuery(“.menu a”).hover(function(){
    jQuery(“#logoid”).attr(‘src’, templateUrl+”/images/global/logo/about.gif”);

    jQuery(“.menu a”).mouseleave(function(){
    jQuery(“#logoid”).attr(‘src’, mylogoimage);


    var templateUrl as you can see is hard coded for now. How do I dynamically reference this
    ‘<?php bloginfo(‘template_directory’); ?>’
    I can’t seem to get the syntax right to call this in my query.
    so when the site changes from staging to live this automatically updated too …..

    I know this should be easy I’m just not a coder.

    Many Many Thanks for any help

Viewing 2 replies - 1 through 2 (of 2 total)
  • Please use backticks around your code (it’s just easier to read).

    Where are you loading this script? If you’re doing

    <script src="myscript.js" />

    it won’t have access to the WP variables, like it will if you put the script between the <head> tags.

    Another option is to wrap your code in a function, which is held in a JS file. You would call the function in the <head> tags and pass the URL in there as a parameter. (See a question on StackOverflow for a probably better explanation.)

    var myFunction = function(url) {
      var templateurl = url;
      // the other stuff

    In the <head> area

    <script src="myjs.js" />
    $.myFunction('<?php bloginfo('template_url'); ?>');



    You can also use wp_localize_script to do this.

    First enqueue your js from functions.php (or a plugin) with wp_enqueue_script

    wp_enqueue_script('myscript', 'location to your script');

    Next call wp_localize_script and reference the script you just enqueued. Also pass an array of values for your script to access. For example, you can get the template uri of the current theme with get_template_directory_uri().

    wp_localize_script('myscript', 'mylocalizedscript', array('myurl' => get_template_directory_uri()));

    the localize function will output the following before your script

    /* <![CDATA[ */
    var mylocalizedscript = {"myurl":"http:\/\/\/staging\/wp-content\/themes\/pitchandco"};
    /* ]]> */

    and inside your script you can access mylocalizedscript.myurl to get at the value you set in php e.g.

    var templateUrl = (mylocalizedscript.myurl);
    /* verify you are getting the correct values */

    As php changes the value from staging to live, the value in your script will also change.

    Otto has a nice tutorial on passing parameters from PHP to Javascript

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘referencing my site path in jquery’ is closed to new replies.