1
votes

I want to restrict certain pages of my WordPress website to logged in users.

To do this I've written some code redirecting users to the login page, and set my membership plugin to then redirect them to the last user page. The problem is that the wp_redirect function does not save the URL, so after logging in the user gets redirected to the page they were on before, rather than the page they were trying to access (the restricted page).

Any help with this annoying problem would be much appreciated! :) My code is below.

function page_redirects() {
  if (is_page("Example") ) {
    if (is_user_logged_in()!) {
        wp_redirect('https://www.barn-door.co.uk/login/');
    }
  }
}
add_action( 'template_redirect', 'page_redirects', 1, 0 );
2
you can create a cookie that stores the original url and then retrieve the cookie and redirect the user after login - Mason
Thanks Sohrab :) Do you know how I could modify my php script to to do this? Perhaps I could use the setcookie() function to store the cookie but do you know how I'd retrieve it after login? - Alex

2 Answers

0
votes

You can accomplish this with a plugin such as: https://wordpress.org/plugins/restrict-user-access/

If you only have a few pages that should be visible for logged-in users, this is probably a better option: Simply go to Pages in the Admin Dashboard and tick the pages you want to restrict. Then in the “Bulk Actions” dropdown select “Edit” and update Status to Private. That’s it! Those pages will only be visible to users that are logged in.

0
votes

It turns out that WP has a handy function for this, auth_redirect() https://developer.wordpress.org/reference/functions/auth_redirect/ Problem solved :)