Get page id for redirections - Wordpress

90 Views Asked by At

I am trying to make a wordpress plugin that redirect a non-logged user to the wordpress login page if he tries to access a restricted page.

function redirection()
{
   $pageid = get_queried_object_id();

   if (!is_user_logged_in()) {
      if ($pageid === 5) {
         wp_redirect('http://localhost/wordpress/login');
         exit();
      } else if ($pageid === 8) {
         wp_redirect('http://localhost/wordpress/login');
         exit();
      } else if ($pageid === 10) {
         wp_redirect('http://localhost/wordpress/login');
         exit();
      }
   }
}

add_action('init', 'redirection');

The problem is that even if the page ID is the good one, the user is not redirected, even if he's not logged in.
I have enabled the wordpress debug mode, and there is not wordpress errors.

the $pageid should be an int, my "test1" page got the ID 5. But it's not redirecting the user.

1

There are 1 best solutions below

0
On BEST ANSWER

After a moment to check with my workmates, we saw that the problem was from the "add_action"

here's the code solution :

function redirection()
{
   $pageid = get_queried_object_id();

   if (!is_user_logged_in()) {

      if (is_page(array('test1'))) { 
         wp_redirect('http://localhost/wordpress/login');
         exit();
      }
   }
}

add_action('template_redirect', 'redirection');