Home » Code Examples » Add session check to posts

March 26, 2021

Add session check to posts

If you dont want to completely block your users from logging in another good option is to use the "is_within_session_limit" filter to add a session check to any post.

add_action("template_redirect", function() {
    // Array with post IDs
    $posts_to_block = array(1,2);

    // Check if current posts is one to protect
    if (!in_array(get_the_ID(), $posts_to_block) ) {

    $within_limit = apply_filters("is_within_session_limit", true, wp_get_current_user());
    if (!$within_limit) {

        // If referrer could be determinde redirect there else home url
        $url = wp_get_referer() === false ? home_url() : wp_get_referer();


Explaination of this snippet

  1. The variable "posts_to_block" contains an array of post ids to check the session limit for
  2. Check if the id of the current post is within the "posts_to_block" variable
  3. Apply the "is_within_session_limit" filter to check if the current user is within the session limit
  4. If not the user gets redirected to the referring page.
    1. If the referring page can not be determined the user gets redirected to the home page

How to add this code snippet?

We recommend that you add the code snippets to your themes functions.php file. Make sure you create backups before you add any customization. Please make sure that you always have a plan ready if a code snippet causes errors. Detailed information about how to add code snippets to your WordPress installation can be found here: wpbeginner.com

Need help customizing session manager?

You are looking for a custom solution, to make the session manager truly fit your needs? No problem we got you covered. Simply send us a short briefing about your requirements and we send you a quote if there is not already a solution. If your problem requires changes on the plugin and we think the new functionality might be a feature many users would like, we implement it in the core of our plugin. This way you profit from features others requested and also be an awesome part of the community.

Leave a Reply

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