Skip to content

Instantly share code, notes, and snippets.

@pablo-sg-pacheco
Last active October 17, 2022 20:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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';
} );
?>
@irfanqasim
Copy link

Hi,
would you like to explain how to use this code inside the plugin for custom post type password protect.

@pablo-sg-pacheco
Copy link
Author

Hi,
What you'd like to know?

@irfanqasim
Copy link

Hi,
i have plugin with custom post type , i want all custom post type to be password protected, when member/user want to access/see post it need to enter password to view CPT

@pablo-sg-pacheco
Copy link
Author

I just updated the gist.

All you need to do is add this code on your functions.php or in your plugin code and replace the 'post' by your post type slug.
Let me know if it works ;)

@irfanqasim
Copy link

Hi,
i have implemented the code in plugin when i published the post and then go to view it shows the CPT and below the message "This content is password protected. To view it please enter your password below". The CPT should be hide until enter password.

@pablo-sg-pacheco
Copy link
Author

Hum, that's odd. I just tried on my end and it works.
Maybe it's a problem with your theme. Try to switch it to Storefront theme for example and check again

@irfanqasim
Copy link

Hi ,
I have simple twenty twelve theme, Did you try with custom post type? I have custom post type.

@pablo-sg-pacheco
Copy link
Author

I'm using WooCommerce and I've tried to use the custom post type 'product' and it works just fine.
When I go view the product, the first thing it shows is the password field and I can see no content from the product at all

@irfanqasim
Copy link

Hi,
I am trying different ways lets see, anyway thanks a lot

@darcikole
Copy link

Thank you so much!!

@pablo-sg-pacheco
Copy link
Author

;)

@arthurclouds
Copy link

Write the password directly in the code?
How about letting the user set/change password as pages/posts?

@pablo-sg-pacheco
Copy link
Author

Hi @arthurclouds ,

How about letting the user set/change password as pages/posts?

In that case, I believe there wouldn't be necessary to add any code, as this is the default WordPress mechanism when you set a page/post visibility as "Password protected".

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