Many of us want to protect certain areas of our wordpress blog. You can easily protect your post, pages, and custom template page with some simple snippets of code.
Let’s review how to protect wordpress template pages, hide and protect post and pages, redirect logged in users to protect the backend dashboard and finally add a custom message for protected pages.
Hide custom template page content from non-logged in users. Same as protect content.
[code]</pre>
<div id="fullpagecontent"><!–?php if (is_user_logged_in()) { ?–>
<!–?php } else { // not logged in ?–>
You must login or sign up to view this page.
<!–?php } ?–>
[/code]
Hide post / page content from non-logged in users. Same as protect content.
[code]
function pippin_logged_in_user_shortcode($atts, $content = null) {
extract( shortcode_atts( array(
‘message’ => ”
), $atts )
);
if(is_user_logged_in()) {
return $content;
} else {
return ‘</pre>
<div class="alert_red" style="color: red;">’ . $message . ‘</div>
<pre>
‘;
}
}
add_shortcode(‘logged_in’, ‘pippin_logged_in_user_shortcode’);
[/code]
[code]
[logged_in message="You must be logged in to view this members only content"]This is text that can only be viewed when logged in[/logged_in]
[/code]
Redirect non-admin from dashboard – hide wordpress backend.
[code]
add_action(‘admin_init’, ‘wpse51831_init’);
function wpse51831_init()
{
if(!current_user_can(‘edit_posts’))
{
wp_redirect(home_url());
exit();
}
}
[/code]
Hide admin bar from subscribers.
[code]
add_filter(‘show_admin_bar’, ‘wpse51831_hide_admin_bar’);
/*
* hide the admin bar for `subscribers`
*
* @uses current_user_can
* @return boolean
*/
function wpse51831_hide_admin_bar($bool)
{
if(!current_user_can(‘edit_posts’))
{
$bool = false;
}
return $bool;
}[/code]