1

I have a drupal site and i want to put all nodes url to all img tags! With bellow code can do this but all img linked to the same post url in the main pages, because take the link of the final post and put to all img. The Code i added to node.tpl.php file.

<script> 
      jQuery(document).ready(function($) {
      $(document).ready(function() {
      $('img').wrap("<a href='<?php print $node_url; ?>' </a>");
    });
    });
</script>

Thank you

1
  • Does your images all render through Drupal 'theme_image'? If so then there exist better solution then using jQuery. And I think if something could be done through PHP better use it.
    – FriOne
    Commented Nov 2, 2014 at 17:19

1 Answer 1

1
  1. There is no reason to wrap document.ready inside another call to document.ready. If it's ready, then it's already ready!
  2. The reason your code does not work is because it is assigning the same link to all images on the page. You want your code to link to the node that contains the image.
  3. I would not use jQuery for this at all. Views+Imagecache were designed to do this sort of thing and they do it well. Use views to create the page, and use when displaying the image use the "Image linked to node" option.
  4. If you really really don't want to do it that way, then change your code to be this to give it proper scope (right now it is affecting images outside the target node and causing your page to get images wrapped in 20 different <a> tags!):

    <script type="text/javascript"> 
      jQuery(document).ready(function($) {
        $('img', '#node-<?php print $node->nid; ?>').each(function() {
          var url = '<?php print $node_url; ?>';
          $(this).wrap('<a href="' url + '"></a>');
        });
      });
    </script>
    
  5. Or better yet, don't add it via php and put this in a js file included by your theme instead:

      jQuery(document).ready(function($) {
        $('article img').each(function() {
          var url = $(this).closest('article').find('h1.node-title a').attr('href');
          $(this).wrap('<a href="' url + '"></a>');
        });
      });
    
2
  • Thank you for respond. I try your code but not working, do not do anything. Commented Nov 2, 2014 at 16:21
  • Your other problem is that you are adding this code to the wrong place. Create a .js file for this code and use your theme to add it. Right now it is getting added to the page about 20 times! (looks like once per article, at least)
    – Coleman
    Commented Nov 2, 2014 at 16:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.