Using WordPress ‘is_ssl()’ PHP function

The is_ssl() WordPress PHP function determines if the current page is being served using SSL.

Usage

$is_ssl = is_ssl();

Parameters

  • None

More information

See WordPress Developer Resources: is_ssl()

Examples

Redirecting to HTTPS

If the current page is not using SSL, redirect the user to the HTTPS version of the same page.

if (!is_ssl()) {
    $https_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    wp_redirect($https_url);
    exit;
}

Display a message in the footer indicating if the current page is using SSL.

function ssl_indication() {
    if (is_ssl()) {
        echo '<p>This page is served using SSL.</p>';
    } else {
        echo '<p>This page is not served using SSL.</p>';
    }
}
add_action('wp_footer', 'ssl_indication');

Loading assets conditionally

Load a different CSS file based on whether the page is served using SSL or not.

function load_ssl_assets() {
    $stylesheet = is_ssl() ? 'style-ssl.css' : 'style-non-ssl.css';
    wp_enqueue_style('my-theme-styles', get_stylesheet_directory_uri() . '/' . $stylesheet);
}
add_action('wp_enqueue_scripts', 'load_ssl_assets');

Using SSL for AJAX requests

Use the current protocol (HTTP or HTTPS) for AJAX requests in WordPress.

function my_ajaxurl() {
    echo '<script type="text/javascript">
        var ajaxurl = "' . admin_url('admin-ajax.php', is_ssl() ? 'https' : 'http') . '";
    </script>';
}
add_action('wp_head', 'my_ajaxurl');

SSL-aware site URL

Create a function that returns the site URL with the appropriate protocol based on SSL usage.

function ssl_aware_site_url() {
    return is_ssl() ? site_url('', 'https') : site_url('', 'http');
}

// Example usage:
$link = ssl_aware_site_url() . '/my-page/';