Family Encyclopedia >> Electronics

How to Require Login for Specific WordPress Posts Using Built-in Functions

As a seasoned WordPress developer with years of experience building membership sites, I've relied on a simple, native feature to create members-only content: forcing users to log in before accessing certain posts. This keeps sensitive information private without plugins.

How to Require Login for Specific WordPress Posts Using Built-in Functions

The key is WordPress's auth_redirect() function. When called on a page, it checks if the visitor is logged in. If not, it seamlessly redirects them to the login page—and after successful login, sends them straight back to the original post.

To implement this, add the following code to your theme's functions.php file. It targets specific post IDs (customize the array as needed):

function my_force_login() {
    global $post;
    if (!is_single()) return;
    $ids = array(188, 185, 171); // Post IDs requiring login
    if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {
        auth_redirect();
    }
}

Next, open your theme's header.php file and add this function call right after the opening <body> tag (or at the very top for best results):

<?php my_force_login(); ?>

This setup is lightweight and secure. For more flexibility—such as restricting by category or adding an admin options page to manage IDs—you can easily extend it based on your needs.

The auth_redirect() function has been available since WordPress 1.5, ensuring broad compatibility.

How to Require Login for Specific WordPress Posts Using Built-in FunctionsTuan Anh (aka Rilwis) is a 25-year-old blogger and web developer from Vietnam. He specializes in PHP, MySQL, and Web 2.0 technologies (CSS, JavaScript, Ajax), with a passion for WordPress. Follow Rilwis on Twitter. Website: Luxury Blog Tips