What’s the correct way to write this jquery attr code? (wordpress)

I have this in my theme’s function file:

$(document).ready(function() {
    $(".ajax-loader").attr("src","<?php bloginfo('template_url'); ?>/images/ajax-loader.gif");
});

However, when it prints, the src prints as <?php bloginfo('template_url'); ?>/images/ajax-loader.gif, that is showing the php code instead of showing my template url. What would be the correct way to write this code?

Related posts

Leave a Reply

1 comment

  1. Is this in a .js file? If so, you can’t place WordPress template tags inside because .js files are not processed by PHP.

    You can either include your code inline within header.php using <script> tags:

    <script type="text/javascript">
    $(document).ready(function() {
        $(".ajax-loader").attr("src","<?php bloginfo('template_url'); ?>/images/ajax-loader.gif");
    });
    </script>
    

    Or change the extension of your JavaScript file from .js to .php, and add this line at the very top:

    <?php header('Content-Type: text/javascript'); ?>
    

    That tells the server to treat this as a JavaScript file, although it’ll be processed by PHP.

    In any case, you’re using .attr() correctly.