i am trying to restrict particular web page using php which should be displayed only to the allowed Ip Addresses and for remaining all IP Address it should not be accessible.


1.The page will be in sub menu list.

2.It should be displayed only to the allowed ip address only

Thank You in advance....

  • How are you trying that? Show us your code.
    – fuxia
    Feb 28, 2017 at 12:54

2 Answers 2


Haven't specifically done this yet but something similar

In the theme page/post template files you can get post id of current post/page by doing

$currentID = get_the_ID();

Then redirect all traffic not from the specified IPs

$ipArr = array('xx.xxx.xxx.xxx', 'xx.xxx.xxx.xxx');

 if (!in_array(@$_SERVER['REMOTE_ADDR'], $ipArr))
    header("Location: http://example.com/myhomepage");
  • Thanks for the suggestion... can you tell me why you have used @ in (@$_SERVER['REMOTE_ADDR'], $ipArr)
    – Praveen
    Feb 28, 2017 at 13:02
  • The @ sign is used to suppress error messages and warnings in PHP when prepended. I'm sorry but it shouldn't have been there since it is not always that good of an idea to use. It might cause some frustrations when debugging a piece of code.
    – marwyk87
    Feb 28, 2017 at 18:27

You can block the access page for all IPs, but a whitelist.

function page_ip_restriction() {
        // Whitelist
        $whitelist = array(

        // Check if current user IP is out of the whitelist, then redirect to home
        if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist))
            wp_redirect(home_url(), 403); // 403 -> Forbiden access
add_action('init', 'page_ip_restriction', 10);

For your submenu, you have two ways, the wordpress one, or a css exclusion. But IMO, WordPress menus are really heavy to use.

If you want better IP address tracking, use a librairy.

Hope it's help you !

  • thanks... but i want block all ip addresses and wanted to allow only some ip address to access
    – Praveen
    Feb 28, 2017 at 13:03
  • '', '', '' are the only allowed here.
    – Elex
    Feb 28, 2017 at 13:07
  • i tried and used the above code but it didn't worked i kept the above code in functions.php @Jean-Rémi LARCELET
    – Praveen
    Mar 2, 2017 at 6:48
  • What do you get, something like a blank page ?
    – Elex
    Mar 2, 2017 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.