Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redirect specific WordPress pages or posts to https
/**
* Redirect specific pages or posts to https
*
* This code assumes the page/post ID to make https is 7000.
* You will need to change that ID to match your site.
*
* @link http://blackhillswebworks.com/?p=5088
*/
add_action( 'template_redirect', 'bhww_front_end_ssl_template_redirect', 2 );
function bhww_front_end_ssl_template_redirect() {
if ( is_single( 7000 ) && ! 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_single( 7000 ) && 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();
}
}
}
// OPTIONAL - Make sure SSL page permalinks are also https - only applies to Posts, not Pages
add_filter( 'pre_post_link', 'bhww_make_page_permalinks_ssl', 10, 3 );
function bhww_make_page_permalinks_ssl( $permalink, $post, $leavename ) {
if ( 7000 == $post->ID )
return preg_replace( '|^http://|', 'https://', $permalink );
return $permalink;
}
@bhwebworks

This comment has been minimized.

Copy link
Owner Author

bhwebworks commented Apr 3, 2015

This Gist is a follow-up to this one, https://gist.github.com/bhwebworks/7233529, and if used together you need to add

&& ! is_single( 7000 )

to the opening IF statement in that other Gist, changing the page/post ID 7000 to your specific ID.

@abacoin

This comment has been minimized.

Copy link

abacoin commented Aug 11, 2015

Hi
Im new in this world, can you tell me if i can change the 7000 for more then one page like (7,8,9)?

Thanks for your help

@bhwebworks

This comment has been minimized.

Copy link
Owner Author

bhwebworks commented Oct 17, 2016

@abacoin,

Sorry I'm late - I just now saw your question.

You can use is_single() with an array, so it would look like this for the page IDs you mentioned:

is_single( array( 7,8,9 ) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.