Blankfield.net

Website Design » Web Application Development » Photography

Hide your password-protected WordPress posts

0 Comments Sunday, May 9th, 2010.

If you’ve been using WordPress for a while, you probably know about password protecting your posts using the “Visibility: Password Protected” field. But did you know the links to the password-protected posts will continue to appear in your recent post lists? Well, here’s a quick little trick you can use to replace the standard widget that will prevent password-protected posts from appearing in your sidebar post list. It involves writing (or at least copying and pasting) a little PHP, so don’t try this if you’re squeamish around code.

Assuming you don’t already have a function called my_recent_posts(), paste this code in your functions.php file:

function my_recent_posts($showposts=5) {
 global $post;
 $q = new WP_Query("post_status=publish&order=DESC&showposts=$showposts");
 if ($q->have_posts()) {
  $p = '<ul>';
  while ($q->have_posts()) {
   $q->the_post();
   // The next line does the trick:
   if ($post->post_password != '') continue;
   $p .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
  }
  $p .= '</ul>';
 }
 return $p;
}

In your Widgets panel, drag the Recent Posts widget away from the sidebar(s) to remove it. Then go into your sidebar.php file and call the function my_recent_posts(). If your theme uses more than one sidebar, you may have to apply this to more than one sidebar file.


<div id="sidebar">
 <div class="widget" id="my-recent-posts">
  <h4>Recent Posts</h4>
  <?php my_recent_posts() ?>
 </div>
</div>

To be sure, password-protected posts are no place to store highly sensitive information; the security involved isn’t exactly NSA-grade. But if you want to keep casual passers-by from seeing that video of your nephew learning to ride his bike, this is a quick and dirty way to accomplish that.

(Tested with WordPress 2.9.)

Leave a comment!