I'm trying to output the post ID in the rel-attribute of the image links that are generated by WordPress when using the Add Media button. I found a way to retrieve the post id and also how to customize the output of the image links via the image_send_to_editor
filter.
To customise the image link code I found following post on this WordPress forums:
function filter_image_send_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt) {
$html = sprintf('<a class="fancybox-img" href="%1$s"><img alt="%2$s" src="%1$s" /></a>', esc_attr(esc_url($url)), esc_attr($title));
return $html;
}
add_filter('image_send_to_editor', 'filter_image_send_to_editor', 10, 8);
The code to get the post id is this:
global $post;
$id = $post->ID;
Now, when I combine the 2 the post ID doesn't get displayed. I want to output the post ID prefixed with lightbox-
but when I look at the generated code the rel-attribute looks like this:
rel="lightbox-"
It seems I cannot retrieve the post ID inside of the filter function. The faulty code I use inside the above filter-function is:
global $post;
$id = $post->ID;
$html = sprintf('<a class="fancybox-img" href="%1$s" rel="lightbox-%3$s"><img alt="%2$s" src="%1$s" /></a>', esc_attr(esc_url($url)), esc_attr($title), esc_attr($id));
return $html;
You may ask, why do I want to attach the post ID to the image links? Well, I'm building a page which displays several posts (and their images) on one long page. I attached a lightbox plugin but I want a seperate lightbox per post. The lightbox plugin I'm using groups the images by rel-attribute. I'm trying to make the rel-attribute look like this: rel="lightbox-972"
where 972 is a post id.
As a workaround I use javascript to make the lightboxes work on a per post basis but it would be nice to learn how to achieve this without the js-fiddling and to learn why this isn't working as expected...