Skip to content

Instantly share code, notes, and snippets.

@chrisdavidmiles
Last active August 24, 2022 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdavidmiles/01ad21767394d6b3770197667c32526a to your computer and use it in GitHub Desktop.
Save chrisdavidmiles/01ad21767394d6b3770197667c32526a to your computer and use it in GitHub Desktop.
WordPress Plugin: Require Auth
<?php
/**
* Plugin Name: Require Auth
* Plugin URI: https://gist.github.com/chrisdavidmiles/01ad21767394d6b3770197667c32526a
* Description: Users must be logged in to WordPress to see site content. If a user is not authenticated, they will be redirected to the login screen.
* Author: Chris David Miles
* Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) die;
function is_wplogin(){
$ABSPATH_MY = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, ABSPATH);
return (
( in_array($ABSPATH_MY.'wp-login.php', get_included_files())
|| in_array($ABSPATH_MY.'wp-register.php', get_included_files()) )
|| (isset($_GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php')
|| $_SERVER['PHP_SELF']== '/wp-login.php'
);
}
add_action('init', function () {
if ( ! is_wplogin() &&
! is_user_logged_in() &&
! defined( 'WP_CLI' ) &&
! defined( 'DOING_AJAX' ) &&
! defined( 'DOING_CRON' ) &&
$pagenow !== 'admin-post.php' &&
$request['path'] !== '/wp-admin/options.php' ) {
wp_redirect(wp_login_url( site_url( add_query_arg( array(), $wp->request ) ) ) );
die();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment