I'm currently building my own website using wordpress. I designed my own login - page and want users to be redirected to that page if they are not logged in.
There are several solutions to this problem, however, none of them seem to work.
I tried:
functions.php, such as:<?php
function admin_redirect() {
if ( ! is_user_logged_in() ) {
wp_redirect( home_url( '/{custom page goes here}/' ) );
exit;
}
}
add_action( 'get_header', 'admin_redirect' );
It apparently didn't work - I also tried some other code like (to my header.php):
<?php
if ( ! is_user_logged_in() ) {
wp_redirect('http://somepagehere');
exit;
}
First of all, installing "Force Login" didn't work when accessing the main page and only prohibited access when adding a slug to the main page (ex.: oho.nachhilfe.de/xyz). It also didn't redirect to the login page, but instead simply redirected to a 404 page (no matter what my login URL was).
Changing my login URL to a custom one using "WPS Hide Login" also didn't work, as this only replaced my custom login page with the default wordpress login page, therefore, my custom page simply got overwritten with the wordpress one.
Any ideas how to solve the issue?
First of all, let's all agree that the login customization handling in WordPress is awful.
Like Chris said, forward compatibility and messing with core don't go well together.
If it's just a permalink question you can always customize them instead of re-creating the whole login system.
Moving on. Both of your spinets are perfectly working, tho get_header is the wrong hook to use. Redirects needs to happen before determining which template to load. which is happening before get_header but after init and wp.
You can use, template_redirect do do just that.
Fires before determining which template to load.
<?php
add_action( 'template_redirect', function () {
if ( ! is_user_logged_in() && ! is_page( 'login' ) ) {
wp_safe_redirect( home_url( '/login/' ) );
exit;
};
} );
You can refer to the WP Plugin API/Action Reference to have a better understanding of the hook firing sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With