Skip to content

Tareq Hasan

Get attachment ID from "Insert into Post|Page" button

We always use this nifty “Insert into Post” button when uploading an image in any type of field, including uploading an 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.

/**
 * 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 );

So now you’ve the HTML5 data attribute and it’s super easy to grab the value.

window.send_to_editor = function(html) {
    var attachment_id = $(html).data('id');

    tb_remove();
};

Easy peasy :-)