Skip to content

Instantly share code, notes, and snippets.

@alanef
Last active March 24, 2019 13:23
Show Gist options
  • Select an option

  • Save alanef/3cca982e8e93fc04d8e8a731ae551f2a to your computer and use it in GitHub Desktop.

Select an option

Save alanef/3cca982e8e93fc04d8e8a731ae551f2a to your computer and use it in GitHub Desktop.
snippet for functions.php or plugin to restrict user access
function restrict_access_if_logged_out(){
if (!is_user_logged_in() ){
$redirect = home_url() . '/wp-login.php?redirect_to=' . get_site_url;
wp_redirect( $redirect );
exit;
} else {
if (!current_user_can('manage_options') && !is_admin()) {
show_admin_bar(false);
}
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Example of how to restrict access to a network or logged in user only

The code could be put into functions.php

Note this is an example, and untested in live and would need to be edited to the right network values

It also isn't that secure as the REMOTE_ADDR can be spoofed so shouldn't be used for really secure content - in which case alternative security measures ( i.e. Single Signon within an organisation) should be used

function restrict_access_if_logged_out(){
if (!is_user_logged_in() ){
$ip = explode('.',getenv( 'REMOTE_ADDR' )); //assume thelocal net is IP IV
if ( true === WP_Http::is_ip_address( $ip ) ) {
if ( '172' == $ip[0] && '10' == $ip[1] && '0' == $ip[2] ) return; // change the parts of ip as required
}
$redirect = home_url() . '/wp-login.php?redirect_to=' . get_site_url;
wp_redirect( $redirect );
exit;
}
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment