{Name (First):7.3} requested the following code from my WordPress AI Code Generator.
when visiting a page called timeline redirect to home page when not logged in
The robot generated the following code:
For this requirement, you can use WordPress's is_page() and auth_redirect() functions to check if a user is visiting the 'timeline' page and if they are not logged in. Our functions will then redirect them to the login page. Here is a code snippet that reflects this, you just need to paste it into your theme's functions.php or a custom functionality plugin:
“`php
add_action( 'template_redirect', 'nm_redirect_to_homepage' );
function nm_redirect_to_homepage() {
if( is_page( 'timeline' ) && ! is_user_logged_in() ) {
auth_redirect();
}
}
“`
The 'nm_redirect_to_homepage' function gets called on the 'template_redirect' action hook. This is one of the last actions that run in the WordPress sequence, thus making it a good hook to use for redirects. This hook is especially good for our case because it is late enough in the process that is_page and is_user_logged_in conditionals will work correctly.
This function first checks if the page being accessed is the 'timeline' page by calling the is_page function with 'timeline' as a parameter. If the current page is the 'timeline' page, the function then checks if the user is logged in with the is_user_logged_in function.
If the user is on the 'timeline' page and is not logged in, the auth_redirect function is called to send the user to the login page. After logging in, the user will be returned to the 'timeline' page.