X
    Categories: Tutorials

Setting target blank to be checked by default in WP

A ticket came up recently requesting that the target _blank checkbox in the WordPress link dialog be checked by default. We link to external sites a lot so it makes a lot of sense. Ok no problem, I thought. WordPress is bound to have an easy hook or two I can use. Well after a lot of Googling I found plenty of methods, none of which appeared to work. So, reluctantly, I went digging.

The Problem

If you take a look in /wordpress/wp-includes/class-wp-editor.php line 1439 you can see that the input is hardcoded without any options or hooks. Humm annoying.

Digging into TinyMCE we see that in version 4.4.3 there’s a default_link_target attribute that can be passed into the config to achieve exactly what we what. Unfortunately that doesn’t work for one of two reasons, either it’s because WordPress currently uses TinyMCE 4.4.1 or it’s because WordPress uses a custom Link dialog popup which doesn’t account for all of TinyMCE’s options. I didn’t bother to investigate which it was.

Ok so there’s clearly no ‘right’ way to do, looks like it’ll be a custom javascript solution then.

The code


	/**
	 * Select target _blank by default.
	 *
	 * Outputs javascript that hooks into the WordPress link dialog
	 * and sets the target _blank checkbox to be selected by default.
	 *
	 * @return null
	 */
	function default_target_blank() {

		?>
		<script>
			jQuery(document).on( 'wplink-open', function( wrap ) {
				if ( jQuery( 'input#wp-link-url' ).val() <= 0 )
					jQuery( 'input#wp-link-target' ).prop('checked', true );
			});
		</script>
		<?php
	}
	add_action( 'admin_footer-post-new.php', 'default_target_blank', 10, 0 );
	add_action( 'admin_footer-post.php', 'default_target_blank', 10, 0 );

The code checks to see if a URL has been entered for the link and if not auto checks the target _blank checkbox. If a URL has been entered it does nothing. Add this code to your functions.php file then on the Post New and Post Edit screens the target blank checkbox will be checked by default for all new links.

Hopefully you’ll find this helpful, any problems let me know in the comments below.

Edward :