Jump to content

Redirect if Not a Specific Page & user not Logged in


n1concepts

Recommended Posts

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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.