urls - Remove the http protocol from images

admin2025-06-03  2

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

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
Share Improve this question asked Jan 8, 2015 at 1:45 brandozzbrandozz 8221 gold badge14 silver badges27 bronze badges 1
  • This could cause issues with 3rd party URLs in hyperlinks not running https – Tom J Nowell Commented Jan 8, 2015 at 2:37
Add a comment  | 

1 Answer 1

Reset to default 8

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

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;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748939046a314991.html

最新回复(0)