Remove the http protocol from images

I’ve been banging my head on the wall trying to filter my posts to remove the http: protocol from the img src and I think I may have found a solution. Does anybody see anything wrong with this solution within the loop:

$content = get_the_content();
$content = str_replace(array('http:', 'https:'), '', $content);

echo $content

1 Answer
1

The code you provided could cause issues with 3rd party URLs in hyperlinks not running https. You can fix this by including your home url, e.g:

$content = str_replace( set_url_scheme( home_url(), 'http' ), set_url_scheme( home_url(), 'relative' ), $content);

Next, you’re applying this when you’d like to display the content, which means you need to do an additional step. Namely, you need to apply a filter called the_content which does some final processing, such as creating paragraphs etc:

$content = get_the_content();
$content = str_replace( set_url_scheme( home_url(), 'http' ), set_url_scheme( home_url(), 'relative' ), $content);
$content = apply_filters( 'the_content', $content );

echo $content

Finally, for maximum compatibility, just call the_content();, and use the the_content filter to do your modification:

add_filter( 'the_content', 'brandozz_url_filter' );

function brandozz_url_filter( $content ) {
    $content = str_replace( set_url_scheme( home_url(), 'http' ), set_url_scheme( home_url(), 'relative' ), $content);
    return $content;
}

Filters and hooks can go inside a plugin or functions.php, this is what it looks like as a plugin:

/**
 * Plugin Name:       Relative local URLs
 * Plugin URI:        http://wordpress.stackexchange.com/questions/174228/remove-the-http-protocol-from-images
 * Description:       Replaces http:// URL containing the home url, with relative protocol urls 
 * Version:           1.0.0
 * Author:            Tom J Nowell
 * Author URI:        http://tomjn.com/
 */

add_filter( 'the_content', 'tomjn_filter_relative_content_urls' );

function tomjn_filter_relative_content_urls( $content ) {
    $content = str_replace( set_url_scheme( home_url(), 'http' ), set_url_scheme( home_url(), 'relative' ), $content);
    return $content;
}

Leave a Comment