Halloween Sale 15% off Ends in See the plans
PHP

Emergency Lockdown Switch

Adds a "Lockdown" toggle to the admin bar for administrators. While it is on, only administrators can log in, everyone else is logged out, registration and comments are closed and XML-RPC is off.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_locked = function () {
    return '1' === get_option( 'wpide_lockdown' );
};

add_action( 'admin_bar_menu', function ( $bar ) use ( $wpide_locked ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $bar->add_node( array(
        'id'    => 'wpide-lockdown',
        'title' => $wpide_locked() ? 'Lockdown: ON' : 'Lockdown: off',
        'href'  => wp_nonce_url( admin_url( 'admin-post.php?action=wpide_lockdown' ), 'wpide_lockdown' ),
        'meta'  => array( 'title' => 'Toggle emergency lockdown' ),
    ) );
}, 999 );

add_action( 'admin_post_wpide_lockdown', function () use ( $wpide_locked ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Sorry, you are not allowed to do that.' ), 403 );
    }

    check_admin_referer( 'wpide_lockdown' );
    update_option( 'wpide_lockdown', $wpide_locked() ? '0' : '1' );
    wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url() );
    exit;
} );

add_action( 'init', function () use ( $wpide_locked ) {
    if ( ! $wpide_locked() ) {
        return;
    }

    add_filter( 'pre_option_users_can_register', '__return_zero' );
    add_filter( 'comments_open', '__return_false', 99 );
    add_filter( 'xmlrpc_enabled', '__return_false' );
    add_filter( 'xmlrpc_methods', '__return_empty_array' );
    add_filter( 'authenticate', function ( $user ) {
        return ( $user instanceof WP_User && ! user_can( $user, 'manage_options' ) ) ? new WP_Error( 'wpide_lockdown', 'Logins are temporarily disabled.' ) : $user;
    }, 99 );

    if ( is_user_logged_in() && ! current_user_can( 'manage_options' ) ) {
        wp_logout();
    }
}, 1 );

Notes

Use it while you investigate a problem; switch it off again from the same admin bar item.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.