Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"get_current_user_id()" strict comparison with number fails

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, 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 and not the first one?

Edit

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

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 );

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading