WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

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
share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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