I need a way to have certain post attachments (images/pdfs/etc) be restricted to specific logged in users.

What is the best way to do this?

At a high level it seem like I need to do the following:

  1. Divert the attachment to a secured folder (eg. outside of the webroot).
  2. Write a controller of some sort to check if the user is allowed to access the file and then output the bits of the file if they are.

I can do step one based on the filename using something like the solution in Change upload directory for PDF files.

However, when I do that I can't figure out how to change the attachment URL that Wordpress generates so that I can do step 2. Wordpress assumes that it's still in the normal upload directory.

So, how do I change the URL when I'm changing the upload directory and is there a better way to go about this?

  • Have you considered adding custom capabilities? codex.wordpress.org/Roles_and_Capabilities Test if a user has cap to allow access? – jdm2112 Nov 13 '15 at 16:31
  • @jdm2112 Yes, but that doesn't prevent someone with the link accessing the file directly. – matthew Nov 13 '15 at 16:33
  • How would they get the link? – jdm2112 Nov 13 '15 at 16:35
  • Copy/paste from a friend? Guessing? Etc. – matthew Nov 13 '15 at 16:41
  • How many images are you trying to restrict and to how many users? You could use a filter to prevent specific imgs from showing to anyone not user x or y but that's highly manual. How about a CPT to house these images and then restrict the pos type to a specific role? – jdm2112 Nov 13 '15 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.