• Resolved Davood Denavi

    (@binarywc)


    I am adding custom post types to a site I am working on using the code found in this article: https://wpeasytuts.com/how-to-create-custom-post-types-in-wordpress-without-plugin/. I’m aware that there are plugins to do this but I am trying to move away from using plugins for stuff like this. On to my question,

    1) Is there a way to make all front-end pages created by these new custom post types require login to view?

    2) Along the same lines, is there a way to make the archive page require login to view?

    Thank in advance for your help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The answer to both questions is yes, but it’s not an option when registering a post type. You would need to achieve it with additional code. The two most straightforward I can think of handling it are:

    1. Inside the templates for the post type, use the function is_user_logged_in() to check if the current user is logged in. If they are, show the normal code for the post type’s content, or if not, show a login form with wp_login_form().
    2. Inside your plugin, or your theme’s functions.php file (wherever you’re registering the post type), hook into the template_redirect hook, and check if the user is logged in. If they are not, redirect to wp-login.php.
    • This reply was modified 6 years, 4 months ago by Jacob Peattie.

    I’m also interested in this, and I know there is a capability parameter on the register function. Couldn’t you make it so it needs more than read_posts to read it? A new cap that you get when you login? Or something like that?

    Moderator bcworkz

    (@bcworkz)

    Joy suggests a logical approach. However, capabilities are not checked when responding to simple view requests, so a check needs to be added in in the manner Jacob suggests, except you check for a capability. It’s probably still a good idea to check logged in status first for a better user experience. The capability check could be viewed as an additional check instead of an alternative restriction.

    Why check capability at all if you still should check logged in status? For greater control over just who can view certain post types. Even if you don’t see the need now, it’ll be easier to manage in the future if capability checking is built in now.

    Thread Starter Davood Denavi

    (@binarywc)

    Thanks for the input guys. I’ve been really busy the last few weeks and I am considering all options. I will let you know what I ended up doing when the project is completed in a couple weeks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Two Custom Post Type questions’ is closed to new replies.