We always use this nifty “Insert into Post” button when uploading image in any types of field, including uploading a image for some meta field or anything else. Then we attach a JavaScript listener on window.send_to_editor
and insert the attachment/image URL to the input field.
Today I needed a way to get the attachment ID instead of the URL. So I added an HTML5 data attribute on the link and grabbed the value.
[php]
/**
* Add an HTML5 data attribute to the link
*
* @param string $html
* @param int $id
* @return string
*/
function wedevs_send_to_editor( $html, $id ) {
return str_replace( ‘<a href’, ‘<a data-id="’ . $id . ‘" href’, $html );
}
add_filter( ‘image_send_to_editor’, ‘wedevs_send_to_editor’, 10, 2 );
[/php]
So now you’ve the HTML5 data attribute and it’s super easy to grab the value.
[javascript]
window.send_to_editor = function(html) {
var attachment_id = $(html).data(‘id’);
tb_remove();
};
[/javascript]
Easy peasy 🙂
One thought on “Get attachment ID from “Insert into Post|Page” button”