n1concepts Posted June 10, 2020 Share Posted June 10, 2020 Hi, I need to modify some code found on Github to redirect if the user is not already logged in as the set 'wp user' from the script or 'admin'. Github link: https://gist.github.com/cliffordp/e8d1d9f732328ba360ad <?php function auto_login() { // @TODO: change these 2 items $loginpageid = '1234'; //Page ID of your login page $loginusername = 'wpusername'; //username of the WordPress user account to impersonate // get this username's ID $user = get_user_by( 'login', $loginusername ); // only attempt to auto-login if at www.site.com/auto-login/ (i.e. www.site.com/?p=1234 ) and a user by that username was found if (!is_page( $loginpageid ) || ! $user instanceof WP_User ) { return; } else { $user_id = $user->ID; // login as this user wp_set_current_user( $user_id, $loginusername ); wp_set_auth_cookie( $user_id ); do_action( 'wp_login', $loginusername, $user ); // redirect to home page after logging in (i.e. don't show content of www.site.com/?p=1234 ) wp_redirect( home_url() ); exit; } } add_action( 'wp', 'auto_login', 1 ); ?> Basically, I want to define in the function php file the logic to redirect viewer to the login page if the following conditions not met: 1. is_page NOT '1234' and/or wpusername not found 2. No user currently logged in (either wpusername or any wp admin) Again, if either of those conditions not met, then the script should redirect to 'wp_login' ----- Can anyone advise what edits can be made to this code to accomplish that goal - thx Quote Link to comment https://forums.phpfreaks.com/topic/310918-redirect-if-not-a-specific-page-user-not-logged-in/ Share on other sites More sharing options...
maxxd Posted June 11, 2020 Share Posted June 11, 2020 If it's one or several predefined page(s), does the built-in password protection not work? It should limit access to either those users with a password or admin/editor permissions. If that doesn't do it, I think I used to use the 'init' hook to check if the user is logged in and any custom permissions associated with that login - it's run after 'set_current_user' so it should be good. Although, it may have been the 'wp_loaded' hook - sorry, it's been a bit. Quote Link to comment https://forums.phpfreaks.com/topic/310918-redirect-if-not-a-specific-page-user-not-logged-in/#findComment-1578821 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.