You are right that global $post
is not set inside the function. Because it is Ajax callback and there is no loop. However Ajax call is sending post ID which you can retrieve as $_POST['post_id']
inside the function.
Please note: In callback function arguments $url
is not the image URL. It is anchor tag URL. So if someone choose none, attachment page or custom URL while inserting image in content then your image will be broken. So please consider using wp_get_attachment_image_src()
instead of URL.
Then complete function will look like this
function filter_image_send_to_editor($html, $id, $caption, $title, $align, $url, $size, $alt) {
$post_id = isset($_POST['post_id']) ? $_POST['post_id'] : 0;
$image_url = wp_get_attachment_image_src($id, $size);
return sprintf('<a class="fancybox-img" href="https://wordpress.stackexchange.com/questions/222440/%1$s" rel="lightbox-%3$s"><img alt="%2$s" src="https://wordpress.stackexchange.com/questions/222440/%1$s" /></a>', $image_url[0], $alt, esc_attr($post_id));
}
add_filter('image_send_to_editor', 'filter_image_send_to_editor', 10, 8);