Description
This function redirects a user who is not logged in to the login page (if one is set in the main options tab).
Parameters
$redirect_to
(string) (optional) URL to redirect back to following login. (default: false)
Usage
$pages = wpmem_user_pages(); if ( ! is_user_logged_in() && ! in_array( wpmem_current_url(), $pages ) ) { wpmem_redirect_to_login(); }
Examples
Redirect all content that is not the login page, register page, or user profile (for forgot password link) to the login page if the user is not logged in:
// Redirects all pages except login, register, and profile url to the login page. // (note: the profile url is needed for password reset which is why it is excluded). /** * Use 'template_redirect' if you might need to use additional functions for * logical tests that need $post data, like is_page() * @see: https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect */ add_action( 'template_redirect', 'my_redirect_to_login' ); function my_redirect_to_login() { // Get an array of user pages with wpmem_user_pages() // @see: https://rocketgeek.com/plugins/wp-members/docs/api-functions/wpmem_user_pages/ $pages = wpmem_user_pages(); // If the user is not logged in, and the current page is not in the user pages array. // @see: https://rocketgeek.com/plugins/wp-members/docs/api-functions/wpmem_current_url/ if ( ! is_user_logged_in() && ! in_array( wpmem_current_url( true, false ), $pages ) ) { // Redirect the user to the login page. wpmem_redirect_to_login(); } return; }
Redirect a specific page to the login page:
// Redirects specified url to the login page. /* * This example makes use of wpmem_current_url() to get the url of the * page the user is currently requesting. See documentation here: * https://rocketgeek.com/plugins/wp-members/docs/api-functions/wpmem_current_url/ */ add_action( 'template_redirect', 'my_redirect_to_login' ); function my_redirect_to_login() { if ( wpmem_current_url() == site_url( '/blog/' ) && ! is_user_logged_in() ) { wpmem_redirect_to_login(); } return; }
Redirect blocked content to login:
add_filter( 'template_redirect', function() { if ( wpmem_is_blocked() && ! is_user_logged_in() ) { wpmem_redirect_to_login(); } });
Notes
- The function automatically applies a redirect back to the requested page. You only need to pass a redirect_to argument in the function if you want to redirect to a URL that is not the requested URL.
- This function can be helpful in situations where you may have something to block that is not handled the same way as ordinary content. Some examples would be custom post types that display content outside of the main $content variable (such as event calendars, forums, etc).
Changelog
- Introduced in version 3.0.2
- Moved to API in 3.1.1
- Added redirect_to argument in 3.1.3
Source
wpmem_redirect_to_login() is located in /includes/api/api.php.