0

on my website I restricted 3 pages (IDs 861, 869, 931) to all non-registered users but I'm having a problem, those pages will always redirect the user to the login page (even if I'm logged in), what I'm doing wrong?

Here's the code, a little help would be greatly apprecieated

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {

if ( is_single('861') or is_single('869') or is_single(931) &&
!is_user_logged_in() ) {

wp_redirect( 'http://mywebsite.com/login', 301 ); 
exit;
 }
}
RubiksCube
  • 3
  • 1
  • 3

3 Answers3

0
if ( is_single('861') or is_single('869') or is_single(931) &&
!is_user_logged_in() )

Shouldn't it be more like?

if ( (is_single('861') || is_single('869') || is_single(931)) &&
    !is_user_logged_in() )

C# conditional AND (&&) OR (||) precedence

In C# && apparently has higher precedence than ||. Better put it into () just in case.

http://php.net/manual/en/language.operators.precedence.php

I mean, maybe PHP too.

kry
  • 362
  • 3
  • 13
0

You if conditional is incorrect. Try this code

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {

if ( is_single('861') || is_single('869') || is_single(931) ) {
    if ( !is_user_logged_in() ) {   
        wp_redirect( 'http://mywebsite.com/login', 301 ); 
        exit;
    }
}
rheeantz
  • 960
  • 8
  • 12
0

It looks like you need to scope your order of operations a little better. You first need to check if you're on any of those pages, and THEN if the user is logged in. So:

add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {

if ( (is_single('861') || is_single('869') || is_single(931)) &&
     !is_user_logged_in()  ) {
    if ( !is_user_logged_in() ) {   
        wp_redirect( 'http://mywebsite.com/login', 301 ); 
        exit;
    }
}

Better yet, you could pass those IDs into the same is_single() call:

if ( is_single(array(861, 869, 931)) && !is_user_logged_in()  ) {
    if ( !is_user_logged_in() ) {   
        wp_redirect( 'http://mywebsite.com/login', 301 ); 
        exit;
    }
}

By the way, why are you using is_single() if you're checking pages? Are these custom post types? You might be better off with is_page().

Alex MacArthur
  • 2,220
  • 1
  • 18
  • 22