Skip to content

Instantly share code, notes, and snippets.

@pablo-sg-pacheco
Last active July 11, 2025 18:18
Show Gist options
  • Save pablo-sg-pacheco/b6ebef644d93f8480b1955b4bed5b052 to your computer and use it in GitHub Desktop.
Save pablo-sg-pacheco/b6ebef644d93f8480b1955b4bed5b052 to your computer and use it in GitHub Desktop.
Wordpress - Password protect a custom post type programmatically
<?php
/**
* Password protects a custom post type programmatically.
*
* @param $post
*/
add_action( 'the_post', function( $post ){
if ( $post->post_type != 'post' ) {
return;
}
$post->post_password = 'your_password';
} );
?>
@Moriaani
Copy link

Moriaani commented Jul 9, 2025

Hi @jerome-toole

thanks for your response!
It would help me a lot if I could at least save the singular posts of my CPT with it. I'll take care of the archives later.

But what exactly do I have to do to get this code running for my singular posts?

So I ask the question again:
Do I have to assign a category for all my custom posts so that they are protected?
And where do I enter my CPT slug in your code? And where do I enter the password?

For example line 4 and 5:
'resources' => 'resources_pass', 'post_type_2' => 'pass2',
What exactly do I enter here?
Must the unencrypted password be entered here?

And what does this mean?
'guides' => 'pass2343',

Thanks for your advice!!

@jerome-toole
Copy link

@Moriaani. Ok, for your single posts, my code was broken up into two sections, one array for Post Types and one for Categories.

In both arrays, the key (on the left) is the name for the PT or Term, and the value is the password in plain text.

            $protected_post_types = [
                'post_type_name' => 'the_password',
                'pt_name_2' => 'password_2',
            ];

            $protected_categories = [
                'guides' => 'password',
                'recipes' => 'password',
                'news' => 'password',
            ];

So in answer to your question:

  • in my current setup, you can either lock down all posts from a particular CPT ($protected_post_types) or you can lock down posts that are in a particular category ($protected_categories).
  • You enter the unencrypted password on the right.
  • 'guides' was an example of a category term name.

Of course, you could extend this logic to work for any taxonomy or any other post metadata.

Jerome

@Moriaani
Copy link

Thank you sooo much, @jerome-toole

Works like a charm ๐Ÿ‘๐Ÿ™‚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment