4

How can I replace wp_get_attachment_image() function without changing the core files. The function doesnt have an action hook or a filter hook.

What I am trying to achieve:

for lazyload plugin output the image html like this:

<img width="150" height="150" data-src="http://localhost/yxz/wp-content/uploads/2010/06/calliope.slide_-150x150.jpg" class="attachment-thumbnail" alt="calliope.slide" src="http://localhost/yxz/wp-content/uploads/blank.png">

instead of this:

<img width="150" height="150" src="http://localhost/yxz/wp-content/uploads/2010/06/calliope.slide_-150x150.jpg" class="attachment-thumbnail" alt="calliope.slide">

2 Answers 2

7

There is a filter, wp_get_attachment_image_attributes, for the image attributes-- a well designed one too.

function alter_att_attributes_wpse_102079($attr) {
  $attr['data-src'] = $attr['src'];
  return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'alter_att_attributes_wpse_102079');

That will add the data-src attribute. That looks like what you need. You could add more attributes, or alter the existing onese, if you need.

2
  • thanks so much!! I edited the code like this to replace the src with my image: function alter_att_attributes_wpse_102079($attr) { $attr['data-src'] = $attr['src']; $attr['src'] = 'i.imgur.com/xTWRCpu.png'; return $attr; } add_filter( 'wp_get_attachment_image_attributes', 'alter_att_attributes_wpse_102079');
    – Towfiq
    Jun 6, 2013 at 14:46
  • Thank you! Still works perfectly, and good for adding alt attributes on images, where the alt is not filled out.
    – Stender
    May 8, 2019 at 11:09
0

You can create another function in your functions.php file and then use it instead of wp_get_attachment_image().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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