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
First, 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 sprintfreturns 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
Thank you for your tutorial!
For some reason, it didn’t work for me….
I’m trying to find a way programmatically add 2-3 additional custom IMG attributes by default to all images (inside Gutenberg blocks).
Example: data-pin-title=”” data-pin-description=””
There are only 2-3 examples but none of them are working.
I already posted a project on Fiverr and some developers are telling me that this is super-complicated and will require weeks of programming.
Can you direct me to
Yeah, unfortunately there isn’t a solution yet. This is the closest track I could find https://github.com/WordPress/gutenberg/issues/10204