WordPress and buddypress programming

Make Content Private

Viewing 0 reply threads
  • Author
    Posts
    • #4546
      Michael Mc
      Keymaster
      @mkmcst

      This solution will allow logged in users to access the post or page, while taking users who are not logged in to a login page.

      The code below is constructed of the following elements:

      • The template_redirect hook: This executes just before WordPress selects the template to load.
      • get_queried_object_id() function: This reads the ID of the user’s current page.
      • An array of page IDs: This will tell the function which pages to restrict to logged in users.

      The example below uses an array named private_pages, set to restrict page IDs 2, 15, and 17. You will need to insert your own page IDs here for the code to work. You will also need to replace “LINK_TO_LOGIN_PAGE” with a link to your login or registration page.

      
      if( !function_exists('private_logged_in_users') ):
       
          add_action( 'template_redirect', 'private_logged_in_users' );
       
          function private_logged_in_users(){
               
              /* Reads the current page ID */
              $page_id = get_queried_object_id();
       
              /* List of IDs restricted to logged-in users */
              $private_pages = [ 2,15,17, ];
            
       
              if( ( !empty($private_pages) && in_array($page_id, $private_pages) ) && !is_user_logged_in() ):
      
      
       
                  wp_die('To view this content, please <a href="LINK_TO_LOGIN_PAGE" target="_blank">log in or register.</a>');
                  return;
                  exit;
       
              endif;
          }
       
      endif;
      
      

      One of the disadvantages of this technique is that the posts and pages you want to make private probably aren’t static. Every time you add a new piece of gated content, you will have to update the page IDs in your array.

      In addition, this doesn’t allow you to restrict access based on membership levels, paid memberships, etc. As long as a user is logged in, they will see the content.

       

Viewing 0 reply threads
  • You must be logged in to reply to this topic.