admin管理员组

文章数量:1134247

I was wondering why (and how to) restricting pages by the following criteria does not work. I wanted to restrict the contact page due to spam. The code is being added and activated on front-end using the Code Snippets plugin:

function contactusnot()
{
    if ( !is_user_logged_in() && (is_page( 220 ) || is_page( 'Contact us' ) || is_page( 'contact-us' ))) 
    {
        header("Location: /");
        exit();
    }
}
add_action('init', 'contactusnot');

I've tried removing the function, hoping it will force the filter to work before anything else and also using only the ID/slug/title one by one. Now working for my Woocommerce site.

I was wondering why (and how to) restricting pages by the following criteria does not work. I wanted to restrict the contact page due to spam. The code is being added and activated on front-end using the Code Snippets plugin:

function contactusnot()
{
    if ( !is_user_logged_in() && (is_page( 220 ) || is_page( 'Contact us' ) || is_page( 'contact-us' ))) 
    {
        header("Location: https://google.com/");
        exit();
    }
}
add_action('init', 'contactusnot');

I've tried removing the function, hoping it will force the filter to work before anything else and also using only the ID/slug/title one by one. Now working for my Woocommerce site.

Share Improve this question asked Jul 30, 2023 at 9:18 Johnny BravoJohnny Bravo 11 bronze badge 2
  • It's possible that Code Snippets loads the code on or after the init hook, which means your code wouldn't execute. Try moving the code outside of the hook callback, and see what happens. – Caleb Commented Jul 31, 2023 at 15:25
  • nothing. no redirect with or without function – Johnny Bravo Commented Jul 31, 2023 at 18:19
Add a comment  | 

1 Answer 1

Reset to default 0

The init hook is called too early for your needs. And you should use wp_redirect(). Try this:

function contactusnot() {
    if ( ! is_user_logged_in() && (is_page( 220 ) || is_page( 'Contact us' ) || is_page( 'contact-us' )))  {
       wp_redirect( 'https://google.com/' ); 
       exit;
    }
}
add_action( 'template_redirect', 'contactusnot' );

本文标签: codeRestrict page to members only does not work for page IDslug or page title