Fix Mixed Content on HTTPS in WordPress

This can be used to fix CloudFlare Flexible SSL as well. When this plugin was written “Always HTTPS” or “Rewrite to HTTPS” features from Cloudflare weren’t available.

<?php
/*
 * Plugin Name: Fix Mixed Content on HTTPS in WordPress
 * Plugin URI: https://cojo.eu/fix-mixed-content-https-wordpress
 * Description: Fix CloudFlare Flexible SSL for all resources.
 * Version: 0.1
 * Author: Teo
 * Author URI: https://cojo.eu
 */

// Fix redirect loop
if ( isset( $_SERVER['HTTP_CF_VISITOR'] ) && strpos( $_SERVER['HTTP_CF_VISITOR'], 'https' ) !== false ):
	$_SERVER['HTTPS'] = 'on';
endif;

// Force fix for all resources, even for resources that are loaded in content or with AJAX.
function fixCloudFlareFlexibleSSLstartOb() {
  ob_start('fixCloudFlareFlexibleSSLstart');
}
function fixCloudFlareFlexibleSSLstart($buffer) {
	// Force this hosts to SSL
	$hosts = array('gravatar.com', 'www.gravatar.com', 'fonts.googleapis.com', 'code.jquery.com');
	$site_host = parse_url(get_site_url(), PHP_URL_HOST);
	$hosts[] = $site_host;
	foreach ($hosts as $host):
		$buffer = str_replace('http://'.$host, 'https://'.$host, $buffer);
	endforeach;
	return $buffer;
}
function fixCloudFlareFlexibleSSLend() {
    ob_end_flush();
}
add_action('init', 'fixCloudFlareFlexibleSSLstartOb', 0);
add_action('wp_footer', 'fixCloudFlareFlexibleSSLend', 999999);