Skip to content

Instantly share code, notes, and snippets.

@pablo-sg-pacheco
Last active April 12, 2024 12:38
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';
} );
?>
@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".

@RushaxOfficial
Copy link

Thanks pablo, works great and super useful - we were looking for keeping the same password for all posts to simplify for users and this makes it very easy and programmable.

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