Last active
May 17, 2020 01:24
-
-
Save kingjmaningo/7c24bfde91609ae71a9238eb63c8cfa1 to your computer and use it in GitHub Desktop.
Page redirect by page or by user role - Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'template_redirect', 'page_redirection' ); | |
function page_redirection() { | |
global $current_user; | |
$user_id = $current_user->ID; | |
$user_info = get_userdata($user_id); | |
$user_role = $user_info->roles[0]; | |
// e.g. Redirect users who are not logged-in from About us page to your home page | |
if ( is_page( 'about-us' );) && !is_user_logged_in() ) { | |
wp_safe_redirect(home_url(), 301); // Use wp_redirect() to redirect to another site, using a hard-coded URL | |
exit; | |
} | |
// e.g. Redirect Subscribers from specific pages to your homepage | |
if ( is_page(array(30,187,282,347)) && is_user_logged_in() && $user_role == 'subscriber' ) { | |
wp_safe_redirect(home_url(), 301); | |
exit; | |
} | |
// e.g. Redirect Customers from specfic pages to your homepage | |
if (is_page( array( 42, 'about-me', 'Contact' ))) && is_user_logged_in() && $user_role == 'customer' ) { | |
wp_safe_redirect(home_url(), 301); | |
exit; | |
} | |
} | |
KEY NOTES: | |
// We don't know for sure whether this is a URL for this site, | |
// so we use wp_safe_redirect() to avoid an open redirect. | |
wp_safe_redirect( $url ); | |
// We are trying to redirect to another site, using a hard-coded URL. | |
wp_redirect( 'https://example.com/some/page' ); | |
// When any single Page is being displayed. | |
is_page(); | |
// When Page 42 (ID) is being displayed. | |
is_page( 42 ); | |
// When the Page with a post_title of "Contact" is being displayed. | |
is_page( 'Contact' ); | |
// When the Page with a post_name (slug) of "about-me" is being displayed. | |
is_page( 'about-me' ); | |
/* | |
* Returns true when the Pages displayed is either post ID 42, | |
* or post_name "about-me", or post_title "Contact". | |
* Note: the array ability was added in version 2.5. | |
*/ | |
is_page( array( 42, 'about-me', 'Contact' ) ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment