Force WordPress Add Media button to insert protocol relative links

Update: Protocol Relative links are considered an anti-pattern according to Paul Irish. Basically, if an asset is available over https:// then it should be served as such for security reasons. Get the updated code here.

Cinchws.com is set up to be ‘HTTPS everywhere’, so every URL on the site enforces the HTTPS protocol (SSL). Any HTTP request gets redirect to HTTPS.

Since we launched in a secure manner the site has run smoothly and we haven’t had some of the issues that can arise if your site has been HTTP for years and later forces HTTPS.

One issue that we have had though, is the WordPress Add Media button. Even though we’re forcing HTTPS everywhere the Media button still inserts links as HTTP. This leads to Mixed Content warnings and a lot of red when looking an an inspector console. Not good.

Thankfully there’s a simple fix, and a big thanks to @ninnypants for letting me know about this hook for the Media insert buttonimage_send_to_editor.

Here’s how to set the Add Media button to insert protocol relative links. Add the following code to either functions.php or your own functions plugin:

[php]
add_filter( ‘image_send_to_editor’, ‘force_protocol_relative’, 10, 9 );

function force_protocol_relative($content) {

$content = str_replace( array(‘http://’,’https://’), ‘//’, $content );

return $content;

}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

See if Cinch is right for you.

Ask us anything. Seriously. Like, what is the air speed velocity of an unladen swallow?

Start a chat right now

Or go ahead and Sign up now