Home > database >  "get_current_user_id()" strict comparison with number fails
"get_current_user_id()" strict comparison with number fails

Time:12-02

I've got a technical question to which I would like to have insights more than a solution.

I hooked a custom function to 'template_include' filter in WordPress functions.php as below to work on a page without it being watchable by anyone else.

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() === 11 ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

So if anyone who's not logged into my account go to a 'ressource' custom post type page, they see it with the standard single.php layout and not with the single-ressource.php layout.

The thing is, it doesn't work as is. I have to change the 11 integer in the strict comparison to '11' string to make it work (see edit), as below.

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() === '11' ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

I went to see the official documentation for the get_current_user_id() function and it seems that they use type casting to return either an integer or 0.

Furthermore, when I do a var_dump(get_current_user_id()) on my front-end, it returns int(11).

Anyone has an idea about why the second code works (see edit) and not the first one?

Edit

As @Bazaim pointed it out, I was just confused about the logic involved.

With the second code, the actual "single-ressource.php" I wanted to hide wasn't hidden to anyone because the logic behind the condition passed was flawed. I was redirecting only users with a user_id equal to a string '11' which is no one because user_id are integers.

The code below works perfectly.

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() !== 11 ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

CodePudding user response:

Your user_id is 11 ?

You require to see single.php :

  • $template to be 'single-ressource.php' : right
  • get_current_user_id() to be 11 : wrong, you want the id not to be 11
  • Related