I’ve used the following to protect individual pages:
First add a field to the Publish Metabox:
add_action( 'post_submitbox_misc_actions', 'my_post_submitbox_misc_actions1' );
function my_post_submitbox_misc_actions1(){
echo '<div class="misc-pub-section my-options">
<input type="checkbox" id="fgpsn_protected_content" name="fgpsn_protected_content" value="true"';
if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' ){ echo ' checked'; }
echo '>
<label for="fgpsn_protected_content">FGPSN Content</label></div>';
}
Then save the meta data – the one flaw currently is that the post must be save first. Then you can check and save the box.
add_action( 'save_post', 'fgpsn_protect_content_save' );
function fgpsn_protect_content_save($post_id)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
/* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */
if(isset($_POST['fgpsn_protected_content'])){
update_post_meta($post_id, 'fgpsn_protected_content', $_POST['fgpsn_protected_content']);
//add_post_meta($postid, 'fgpsn_update_zillow_feed_result', 1, true );
}
else{
update_post_meta($post_id, 'fgpsn_protected_content', 'false');
}
}
Finally, add the check:
add_action( 'get_header', 'site_access_filter' );
function site_access_filter() {
if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' && is_user_logged_in() === false ) {
wp_redirect( 'http://fgpsn.com/login' ); exit;
}
}
Obviously, I redirect users to the login page but you could manage this anyway you want from here.