Estimated Reading Time: 3 min
Redirecting non-logged-in users to the login page in WordPress after a certain period of inactivity can be accomplished by adding a custom script to your WordPress theme or through a plugin. Below is a step-by-step guide on how you can achieve this:
Method 1: Adding Code to the Theme’s functions.php
File
- Access Your Theme’s Functions File:
- Go to your WordPress dashboard.
- Navigate to
Appearance > Theme Editor
. - Find and open the
functions.php
file of your active theme.
- Add the Following Code:
function redirect_non_logged_in_users() {
if (!is_user_logged_in()) {
?>
<script type="text/javascript">
setTimeout(function() {
window.location.href = "<?php echo wp_login_url(); ?>";
}, 120000); // 120000 milliseconds = 2 minutes
</script>
<?php
}
}
add_action('wp_footer', 'redirect_non_logged_in_users');
Explanation:
- This code adds a JavaScript snippet to the footer of your WordPress site for non-logged-in users.
- The
setTimeout
function is used to redirect users to the login page after 2 minutes (120,000 milliseconds).
- Save the Changes:
- Click on the
Update File
button to save your changes.
Method 2: Using a Custom Plugin
If you’re not comfortable editing your theme files directly, you can create a custom plugin to handle the redirection:
- Create a New Plugin File:
- Go to
wp-content/plugins
directory. - Create a new folder named
redirect-non-logged-in-users
. - Inside this folder, create a file named
redirect-non-logged-in-users.php
.
- Add the Plugin Code:
<?php
/*
Plugin Name: Redirect Non-Logged-In Users
Description: Redirects non-logged-in users to the login page after 2 minutes of inactivity.
Version: 1.0
Author: Your Name
*/
function redirect_non_logged_in_users() {
if (!is_user_logged_in()) {
?>
<script type="text/javascript">
setTimeout(function() {
window.location.href = "<?php echo wp_login_url(); ?>";
}, 120000); // 120000 milliseconds = 2 minutes
</script>
<?php
}
}
add_action('wp_footer', 'redirect_non_logged_in_users');
- Activate the Plugin:
- Go to your WordPress dashboard.
- Navigate to
Plugins > Installed Plugins
. - Find the
Redirect Non-Logged-In Users
plugin and clickActivate
.
Important Considerations
- Backup: Always back up your site before making any changes to the code.
- Child Theme: If you’re editing the
functions.php
file, consider using a child theme to prevent your changes from being overwritten during theme updates. - Test: Ensure to test the functionality to make sure it behaves as expected and doesn’t interfere with other parts of your site.
This setup should help ensure that non-logged-in users are redirected to the login page after 2 minutes, enhancing the security or user flow of your WordPress site as needed.