TransWikia.com

Custom posts password protect

WordPress Development Asked by Jason on August 6, 2020

my site is highly based on clients and we want to have very strong password protection for a certain custom type post.

We have a custom type post named “something” and here is it’s declaration:

$args = array (
            'label' => 'Something',
            'singular_label' => 'Something',
            'public' => false,
            'publicly_queryable' => true,
            'show_ui' => true,
            'capability_type' => 'post',
            'hierarchical' => false,
            'rewrite' => array('slug' => "something"),
            'query_var' => false,
            'menu_icon' => 'dashicons-chart-area',
            'supports' => array('title')
    );

I want to make sure anything that’s under slug “something” is password protected and if a post with type “something” has a password set, then it asks users to enter the password.

One problem that I’m encountering with this custom post type declaration is, it doesn’t even ask users to enter a password even if password is set.

One Answer

Use post_password_required() function to check if the post is protected.

<?php
global $post;

$p = $post; // can be post object
// $p = $post->ID; // also can be post ID

$post_type = get_post_type($p);

if($post_type = 'something') {  // check post type

    if( !post_password_required($p) ) {
        // unprotected, loop here
    }
    else {
        // protected, show password form
        echo get_the_password_form($p);
    }

}

If you use custom template for this post type you can skip post type check.

However, the code above was not tested.

Answered by Max Yudin on August 6, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP