383

How to Protect Your WordPress Posts with a Password

Protect your WordPress posts with passwords. This guide shows you how to secure your content before publishing your site live, enhancing your site’s SEO and security.


add_action( 'oxygen_enqueue_scripts', 'call_oxygen_vsb_register_condition_post_password_protected' );
/**
 * Run oxygen_vsb_register_condition().
 */
function call_oxygen_vsb_register_condition_post_password_protected() {
    if ( function_exists( 'oxygen_vsb_register_condition' ) ) {
    	oxygen_vsb_register_condition(
    		// Condition Name
    		'Post Password Protected',
    
    		// Values: The array of pre-set values the user can choose from.
    		// Set the custom key's value to true to allow users to input custom values.
    		array( 
    			'options' => array( 'true', 'false' ),
    			'custom' => false
    		),
    
    		// Operators
    		array( '==' ),
    		
    		// Callback Function: Name of function that will be used to handle the condition
    		'post_password_protected_callback',
    
    		// Condition Category: Default ones are Archive, Author, Other, Post, User
    		'Post'
    	);
    }
}

/**
 * Callback function to handle the condition.
 * @param  mixed 	$value    	Input value - in this case, true or false selected by the user.
 * @param  string 	$operator 	Comparison operator selected by the user.
 *
 * @return boolean 				true or false.
 */
function post_password_protected_callback( $value, $operator ) {
	global $post;
	
	return 'true' === $value ? post_password_required( $post ) : ! post_password_required( $post );
}

Other Snippets

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.