0

I created a kind of customer area using several password-protected posts (for more details check this, but it's not necessary for this new issue: Give visitor access to password protected page/post via external script)

On these posts there are several files attached via the plugin "Attachments" (http://wordpress.org/plugins/attachments/). Now, of course I want to prevent the capability to download the files via the direct access but just with the correct login data, so I googled and found this: http://www.stephenharris.info/2012/restricting-direct-access-to-files-in-wordpress/

Short review so you don't have to read it completely:

  1. the root .htaccess file is modified so everything (also files in /upload/) will be redirected to index.php
  2. an action/function called "maybe_load_file" is added which checks whether the request is coming from the uploads folder and if so outputs the file.

My idea was to create a file like "download-redirect.php?id=x". It checks if file with the id x exists, if the referrer is an event post, and if the password cookie is valid. Then it should check if file with the id x is attached to event/post xyz, if all of this is true a session variable with password hash and stuff would be set and the user would be redirected to the file path (see above). In my function "maybe_load_file" I would recheck if the referrer is download-redirect.php and if the session variable is set correctly and then output the files.

So this is my final question, sorry for my long introduction but I think it is necessary to understand the issue: How can I check if a file A is attached (via the plugin "attachments") to post B?

2
  • Are you talking about a plugin called "attachments" or just regular post attachments?
    – Wyck
    Commented Jul 8, 2013 at 19:02
  • I mean this plugin: wordpress.org/plugins/attachments
    – luke
    Commented Jul 8, 2013 at 20:19

1 Answer 1

0

Get all attachments:

$attachments = get_posts( array(
'post_type' => 'attachment',
'numberposts' => -1,
) );

Check attachment "parent" for each attachment.

foreach($attachments as $attachment){
$parentID = $attachment->post_parent;
$postID = $post->ID;
if($parentID == $postID){
  //your code here
  echo 'This attachment belongs to the current post.';
  }
}

But if you already have the attachment, all you need is: note: By "have" i mean you previously queried it or saved it into a object previously.

$parentID = $attachment->post_parent;
$postID = $post->ID;
if($parentID == $postID){
  //your code here
  echo 'This attachment belongs to the current post.';
  }
1
  • But what if an attachment got multiple parents/multiple posts which use this attachment?
    – luke
    Commented Jul 10, 2013 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.