Well… WordPress uses the wpeditimage
tinymce plugin to perform the tasks for the “Add Media” editor button.
When you click the pencil icon to edit the image… the wpeditimage
plugin will read the image code, and determine if there is a value of _blank
for the target
attribute.
If the value is _blank
; the plugin will check the box when the modal window is opened. If not, the box is left unchecked.
You can see this code in action in wp-includes/js/tinymce/plugins/wpeditimage/plugin.js
, at line number 217:
metadata.linkTargetBlank = dom.getAttrib( link, 'target' ) === '_blank' ? true : false;
So… to be checked by default… each time an image is inserted into the editor.. it would need to also have the following attribute and value; target="_blank"
.
Now… the only way to get the box to be checked… is to already have the value of target="_blank"
on the <a>
link wrapping the image when inserting into the editor. For this; we will use the image_send_to_editor filter.
add_filter('image_send_to_editor', 'my_add_target_blank', 10, 8);
function my_add_target_blank($html, $id, $caption, $title, $align, $url, $size, $alt="" ){
// check if there is already a target value
if ( preg_match('/<a.*? target=".*?">/', $html) ) {
$html = preg_replace('/(<a.*? target=".*?)(".*?>)/', '$1 ' . '_blank' . '$2', $html);
} else {
$html = preg_replace('/(<a.*?)>/', '$1 target="' . '_blank' . '" >', $html);
}
return $html;
}
That should take care of adding the target="_blank"
attribute to the <a>
tag wrapping the inserted image.
Now, if you click to edit the image (right after insertion)… you’ll notice the “Open link in new tab/window” option is now checked.
Happy Coding!