This function hides all WordPress content from users who are not logged in. Visitors will see a custom message instead of any pages or posts, except for the login page.

07/10/2024
Back to Gists
<?php
/**
 * Hide entire site unless logged in.
 *
 * Gist Keywords: wordpress, privacy
 * Author: Knol Aust
 * Version: 1.0.0
 * Description: This function hides all WordPress content from users who are not logged in. Visitors will see a custom message instead of any pages or posts, except for the login page.
 */

function ka_hide_wordpress_for_guests() {
    // If user is not logged in and not accessing the login page
    if (!is_user_logged_in() && !is_admin() && !in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'))) {
        // Output the custom message
        wp_die('<h1 style="text-align: center">Hello there, stranger.</h1>', 'Nothing to see here.', array('response' => 200));
    }
}

// Hook the function to the template_redirect action
add_action('template_redirect', 'ka_hide_wordpress_for_guests');

/**
 * Instructions:
 * 1. Add this code to your theme's functions.php file or create a new plugin file with this code.
 * 2. Save the file as ka-hide-wordpress-for-guests.php in your theme directory or wp-content/plugins/ directory.
 * 3. If saved as a plugin, activate the plugin from the WordPress admin panel.
 * 4. Ensure you are logged out to test the functionality. Visitors will see the custom message instead of any page content.
 */