How to Restrict Access to WordPress Pages or Posts for Logged-In Users and Custom Criteria

In WordPress, you can restrict access to certain pages or posts, making them available only to logged-in users. However, what if you want to take it a step further and restrict access based on custom criteria, such as user roles or specific custom fields? In this tutorial, we’ll show you how to restrict access not only to logged-in users but also to specific content based on your chosen criteria.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Basic Access Restriction

To get started, you’ll need to access your WordPress theme’s functions.php file. This file serves as the central hub for customizing your theme’s functionality. You can do this through a code editor or use the built-in Theme Editor within your WordPress dashboard.

Now, let’s add the basic code snippet that restricts access to logged-in users. Add the following code snippet at the end of your functions.php file:

if (!function_exists('restrict_access_to_logged_in_users')) {

    add_action('template_redirect', 'restrict_access_to_logged_in_users');

    function restrict_access_to_logged_in_users()
    {
        // Get the current page or post ID
        $page_id = get_queried_object_id();

        // Define the login page ID (replace with your login page's actual ID)
        $login_page_id = 1;

        // Check if the user is not logged in and not on the login page
        if (!is_user_logged_in() && $page_id !== $login_page_id) {
            // Display a message to non-logged-in users
            wp_die('<style>html{background:#000; text-align:center; color:#fff;}</style><h1>Access Restricted</h1><p>Sorry, this content is available only to logged-in users. Please <a style="color:#fff;" href="' . wp_login_url() . '">login</a> or <a style="color:#fff;" href="' . wp_registration_url() . '">register</a> to access this content.</p>');
        }
    }
}
Code language: PHP (php)

Explanation:

  • We start by checking if a function named restrict_access_to_logged_in_users doesn’t already exist to prevent conflicts.
  • We use the add_action function to hook into the template_redirect action, which fires just before WordPress determines what template page to load.
  • Inside the restrict_access_to_logged_in_users function:
  • We obtain the current page or post ID using get_queried_object_id().
  • We define the ID of your login page (replace 1 with the actual ID of your login page).
  • We check if the user is not logged in (!is_user_logged_in()) and is not on the login page ($page_id !== $login_page_id).
  • If the conditions are met, we use wp_die() to display a custom message and restrict access to non-logged-in users.

Additional Information:

This basic method ensures that only logged-in users can access your WordPress pages or posts. For instance, if you have premium content that should only be visible to registered users, this approach accomplishes just that.

Restricting Access Based on User Roles

In some cases, you may want to limit access to certain user roles. For instance, you might have content that’s exclusively available to premium members or administrators. Let’s modify the code snippet from before to achieve this:

Modifying the Code for User Role Restriction:

if (!function_exists('restrict_access_to_logged_in_users')) {

    add_action('template_redirect', 'restrict_access_to_logged_in_users');

    function restrict_access_to_logged_in_users()
    {
        // Get the current page or post ID
        $page_id = get_queried_object_id();

        // Define the login page ID (replace with your login page's actual ID)
        $login_page_id = 1;

        // Check if the user is not logged in, not on the login page, and not a premium member
        if (!is_user_logged_in() && $page_id !== $login_page_id && !current_user_can('premium_member')) {
            // Display a message to non-logged-in users
            wp_die('<style>html{background:#000; text-align:center; color:#fff;}</style><h1>Access Restricted</h1><p>Sorry, this content is available only to premium members. Please <a style="color:#fff;" href="' . wp_login_url() . '">login</a> or <a style="color:#fff;" href="' . wp_registration_url() . '">register</a> to access this content.</p>');
        }
    }
}
Code language: PHP (php)

Explanation:

  • We’ve added an additional condition to restrict access to non-logged-in users who are not premium members (!current_user_can('premium_member')).
  • This code modification allows you to specify which user roles have access to particular content.

Additional Information:

By incorporating this modification, you can specify which user roles have access to particular content. For example, you can create a “premium_member” user role and limit access to exclusive content to users with that role.

Advanced Custom Criteria (e.g., Custom Fields)

Sometimes, you may require more advanced access restrictions based on custom criteria, such as custom fields assigned to your pages or posts. While we won’t go into detail here, let’s assume you have a custom field set up:

Key: access_level
Value: full_access
Code language: PHP (php)

With this setup, you can modify the code to account for the custom field access_level:

if (!function_exists('restrict_access_to_logged_in_users')) {

    add_action('template_redirect', 'restrict_access_to_logged_in_users');

    function restrict_access_to_logged_in_users()
    {
        // Get the current page or post ID
        $page_id = get_queried_object_id();

        // Define the login page ID (replace with your login page's actual ID)
        $login_page_id = 1;

        // Get the value of the 'access_level' custom field
        $access_level = get_post_meta($page_id, 'access_level', true);

        // Check if the user is not logged in, not on the login page, and doesn't have the required access level
        if (!is_user_logged_in() && $page_id !== $login_page_id && $access_level !== 'full_access') {
            // Display a message to non-logged-in users
            wp_die('<style>html{background:#000; text-align:center; color:#fff;}</style><h1>Access Restricted</h1><p>Sorry, this content is available only to users with full access. Please <a style="color:#fff;" href="' . wp_login_url() . '">login</a> or <a style="color:#fff;" href="' . wp_registration_url() . '">register</a> to access this content.</p>');
        }
    }
}
Code language: PHP (php)

Explanation:

  • We’ve introduced a custom field named ‘access_level’ to pages or posts, allowing you to specify different access levels.
  • We use get_post_meta() to retrieve the value of the custom field.
  • The code restricts access to non-logged-in users who are not on the login page ($page_id !== $login_page_id) and do not have the required access level ($access_level !== 'full_access').

Additional Information:

This advanced method provides you with granular control over access to your content. By assigning specific access levels using custom fields, you can tailor access permissions according to your unique requirements.

That’s it! In this tutorial, we’ve covered various methods to restrict access to your WordPress pages or posts based on different criteria, including user roles. By implementing these code snippets, you can control who can view specific content on your WordPress site.

For a more basic approach to restricting access to your entire WordPress site for non-logged-in users, you can refer to our tutorial on How to Restrict Access to Your WordPress Site for Non-Logged-In Users. This tutorial provides a fundamental method to protect your site’s content from unauthorized access.

Leave your feedback and help us improve ๐Ÿถ

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee โ˜•๏ธ or donating via PayPal ๐Ÿ’ฐ.

More free knowledge, because why not?

Your thoughts matter, leave a reply ๐Ÿ’ฌ

Your email address will not be published. Required fields are marked *