Force SSL On Certain WordPress Pages

There are going to be certain pages that you want to force SSL, so that the browser will redirect you to this page using a HTTPS connection so the data that is posted from this page is encrypted and secure.

This might be for any custom login pages you create in your application, or a credit card payment page. Normally you will have to write a script to force this page to be in SSL, but if you are making your application with WordPress you can use WordPress to redirect the browser to HTTPS by using the force_ssl filter.

This filter will run on every page and is used to decide if WordPress should redirect to HTTPS. Returning true from this function will automatically redirect the user to HTTPS and allow you to collect secure data from this page.

In the example below we can add this code to our functions.php file we can check what the post ID is and return true on certain posts.

function wp_secure_page_force_ssl( $force_ssl, $post_id = 0 ) {
    $force_ssl_on_these_posts = array(100, 150, 190);

    if(in_array($post_id, $force_ssl_on_these_posts )) {
        return true;
    }

    return $force_ssl;
}
add_filter('force_ssl' , 'wp_secure_page_force_ssl', 1, 3);

Advertise here 50% Off

Comment