how to use wp_redirect inside a function

You do not get that error because it runs inside a function, but because the headers have already been send. This means your server already has send some information about the page to the client, thus is it unable to change it’s headers (headers are the first thing that gets send). This mostly happens after something gets echo’ed.

There are a few things you can do to prevent this from happening:

  • Choose another event that gets triggered before the headers are send
  • Remove any echo’ed text or HTML before the redirect
  • Check if there is no whitespace (spaces, enters, tabs) between the the start of your file and the <?php tag.
  • Change your server configration to send the headers later (this can be tricky or inpossible).