How do I force SSL for specific Post or Pages?

For most WordPress websites it is not necessary to have the entire website behind an SSL connection. Sometimes we only need it forĀ a login or a checkout system.

Solution:

  1. Add the following to your templates functions.php. Change the '$force_ssl_on_these_posts' array by adding your post / page ids

    add_action( 'template_redirect', 'fb_ssl_template_redirect', 1 );
    function fb_ssl_template_redirect() {
    	
    	// Add your PAGE / POST ID to the array below
    	$force_ssl_on_these_posts = array(POST ID, POST ID);
    
    	foreach( $force_ssl_on_these_posts as $sslpostid) {
    		if ( is_page( $sslpostid ) && !is_ssl() ) {
    			if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
    				wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']), 301 );
    				exit();
    			} else {
    				wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
    				exit();
    			}
    		} else if ( !is_page( $sslpostid ) && is_ssl() && !is_admin() ) {
    
    			if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
    				wp_redirect(preg_replace('|^https://|', 'http://', $_SERVER['REQUEST_URI']), 301 );
    				exit();
    			} else {
    				wp_redirect('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
    				exit();
    			}
    		}
    	}
    
    }