Skip to content

Instantly share code, notes, and snippets.

@mathetos
Last active July 3, 2018 08:21
Show Gist options
  • Save mathetos/b93c896ad17834d8f218 to your computer and use it in GitHub Desktop.
Save mathetos/b93c896ad17834d8f218 to your computer and use it in GitHub Desktop.
Force http/s for images in WordPress
/**
*
* Force http/s for images in WordPress
*
* Source:
* https://core.trac.wordpress.org/ticket/15928#comment:63
*
* @param $url
* @param $post_id
*
* @return string
*/
function ssl_post_thumbnail_urls( $url, $post_id ) {
//Skip file attachments
if ( ! wp_attachment_is_image( $post_id ) ) {
return $url;
}
//Correct protocol for https connections
list( $protocol, $uri ) = explode( '://', $url, 2 );
if ( is_ssl() ) {
if ( 'http' == $protocol ) {
$protocol = 'https';
}
} else {
if ( 'https' == $protocol ) {
$protocol = 'http';
}
}
return $protocol . '://' . $uri;
}
add_filter( 'wp_get_attachment_url', 'ssl_post_thumbnail_urls', 10, 2 );
@Shelob9
Copy link

Shelob9 commented Jun 13, 2016

function ssl_post_thumbnail_urls

add_filter( 'wp_get_attachment_url', function( $url, $post_id ) {

    //Skip file attachments
    if ( ! wp_attachment_is_image( $post_id ) ) {
        return $url;
    }

    //Correct protocol for https connections
    list( $protocol, $uri ) = explode( '://', $url, 2 );

    if ( is_ssl() ) {
        if ( 'http' == $protocol ) {
            $protocol = 'https';
        }
    } else {
        if ( 'https' == $protocol ) {
            $protocol = 'http';
        }
    }

    return $protocol . '://' . $uri;
}, 10, 2 );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment