Created
February 5, 2024 18:32
-
-
Save alanef/8f5b51b7777065f83e3092c247dc6794 to your computer and use it in GitHub Desktop.
Restrict site to logged in user
This file contains hidden or 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 | |
/* | |
* Plugin Name: Restrict a site | |
*/ | |
// If this file is called directly, abort. | |
if ( ! defined( 'WPINC' ) ) { | |
die; | |
} | |
// Hook 'redirect_if_not_logged_in' function into 'template_redirect' action | |
add_action('template_redirect', '1sw2_redirect_if_not_logged_in'); | |
function 1sw2_redirect_if_not_logged_in() { | |
// Check if user isn't logged in | |
if ( ! is_user_logged_in() ) { | |
// If not logged in, redirect to login form | |
auth_redirect(); | |
} | |
} | |
// hook on login | |
add_action('wp_login', '1sw2_redirect_subscriber_on_login', 10, 2); | |
function 1sw2_redirect_subscriber_on_login($user_login, $user) { | |
// make subscriber go to home page | |
if (in_array('subscriber', (array) $user->roles)) { | |
// Redirect to homepage | |
wp_redirect(home_url()); | |
exit(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment