Add data attribute to images in WordPress posts and pages

Sometimes you need to customize the standard data attributes attached to an image added to the post or page content in WordPress.  For example if you want to implement Lokesh Dhakar’s good old trusty Lightbox2 script you would need to have a new data attribute added to the a href around the image

data-lighbox attributeFirst, let’s have a look what information can we add to an image when uploading an image in the Add Media interface (click on image to see larger version):
You can at least fill in the title field (which is anyway pre-populated with the image name). So we could use this to have a value for the data-lightbox attribute. But how can you add the data-lightbox attribute automatically so you don’t have to edit the html tag each time you add an image in WordPress?

Using the image_send_to_editor filter

Adding filters in WordPress is very easy. Filters are functions added to the functions.php file inside your theme folder that modify the regular html output. In the example below, I want to add the data-lightbox attribute to my image and have the value of the image title (click on image to see larger version)

Let’s see the code:

Let’s explain the code:

  • image_send_to_editor filter changes the image html code after you add an image with the Add Media Button
  • $post_id = isset($_POST['post_id']) ? $_POST['post_id'] : 0; gets the id of the image that is saved
  • $image_url = wp_get_attachment_image_src($id, $size); – get’s the image URL
  • return sprintf returns the new html code for the image. If you look at the data-lightbox attribute – it is replaced with the second value after the comma