Skip to content

Instantly share code, notes, and snippets.

@ajvillegas
Last active February 9, 2021 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajvillegas/9a9a86c13afd6a0022661cd62e7e58eb to your computer and use it in GitHub Desktop.
Save ajvillegas/9a9a86c13afd6a0022661cd62e7e58eb to your computer and use it in GitHub Desktop.
Password protect posts in WordPress programmatically.
<?php
add_action( 'the_post', 'myprefix_password_protect_post_type' );
/**
* Add master password to post type.
*
* This function password protects all posts in
* a post type with the same master password.
*
* @since 1.0.0
*
* @param WP_Post $post The Post object (passed by reference).
*/
function myprefix_password_protect_post_type( $post ) {
// Bail if current post is not from specified post type.
if ( 'page' !== $post->post_type ) {
return;
}
// Assign master password string.
$post->post_password = 'my-password';
}
add_action( 'the_post', 'myprefix_password_protect_category' );
/**
* Add master password to a post category.
*
* This function password protects all posts in a
* category with the same master password.
*
* @since 1.0.0
*
* @param WP_Post $post The Post object (passed by reference).
*/
function myprefix_password_protect_category( $post ) {
// Bail if current post is not from specified category.
if ( ! in_category( array( 'uncategorized' ) ) ) {
return;
}
// Assign master password string.
$post->post_password = 'my-password';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment