Locked/Unlocked in title

This should be incredibly easy, but I’m missing something. This code should simply work if they have entered their password into a password protected post/page. The idea is to remind them it is protected.

However… I can’t get it to work at all. The if statement never returns true. For some reason, I don’t think the function is getting $post.

function unlocked() {
  if(!empty($post->post_password) && !post_password_required()) {
    echo 'unlocked icon reminding them this was protected and they put in their password already';
  }
}

Solutions Collecting From Web of "Locked/Unlocked in title"

Your function will never “get” $post as this is not how functions work. Functions cannot pull anything into itself by itself. If you have debug turned on, you will get a definite bug notice that $post in undefined…..

You would need to invoke the $post global inside your function for anything to work that relies on the $post global, so the following would work

function unlocked() {
  global $post;

  if(!empty($post->post_password) && !post_password_required()) {
    echo 'unlocked icon reminding them this was protected and they put in their password already';
  }
}