2

I have a page, outside the loop, that display a media attachment with some basic info about it (title, uploaded date, etc). I have the attachment ID available to me via a form submitted before the page loads.

What I need to do is secure the page by making sure that only users who have uploaded that file have access to the page with that file one it. In order to do that, I assumed the easiest way would be to compare the ID of the current, logged-in user with the ID of the user who created the attachment. But there doesn't seems to be a way that I can find to get the ID of the author of a post outside of the loop using only the attachment ID.

I'm stumped, how should I do this?

1

Back in the day I wrote a function to check for that (you can put it in functions.php and call it from your page):

public function check_if_user_is_author($user_id, $post_id) {
    global $wpdb;
    $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->posts ." WHERE ID = %d AND post_author = %d LIMIT 1", $post_id, $user_id));
    if(isset($res) && count($res) > 0) {
        return $res[0];
    } else {
        return false;
    }
}

Also, theoretically you could just get the post object and compare the author's ID with the current logged in user's ID. Disclaimer: code below is untested.

$current_user_id = get_current_user_id();
$post_data = get_post($your_att_id, ARRAY_A);
$author_id = $post_data['post_author'];
if( $current_user_id == $author_id ) {
    // good, current logged-in user is author of attachment
}
  • Of course! How simple is just getting the post object, should have thought of that. Nice function too, I'm going to save that one for sure. Thanks! – Eckstein Apr 7 '13 at 6:00

Your Answer

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

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