Title: Attachment&#8217;s corresponding post&#8217;s ID &#8211;&gt; PHP Variable?
Last modified: August 18, 2016

---

# Attachment’s corresponding post’s ID –> PHP Variable?

 *  Resolved [theiconoclast31](https://wordpress.org/support/users/theiconoclast31/)
 * (@theiconoclast31)
 * [18 years, 11 months ago](https://wordpress.org/support/topic/attachments-corresponding-posts-id-gt-php-variable/)
 * I’m creating a plugin that resizes uploaded images and autogenerates thumbs in
   a designated uploads/iconothumbs folder.
 * **Short version**: I have the attachment info – I’d like to get the corresponding
   post’s id, and store it in a variable.
 * **Long version**: I’ve done all the resizing. I’d like to store the new, resized
   thumbnails into files. However, I don’t know how to name the files.
 * The filename should be a) unique and b) echo-able from within the loop, with 
   the post info, but without the attachment info.
 * I’m working from the `wp_handle_upload` filter hook. I understand that each attachment
   has its own ID, but _I need to somehow relate the thumbnails to their corresponding
   post_. In the end, I want to have some kind of `<?php iconothumb1(); ?>` tag 
   that automatically generates the thumbnail for a given post from the loop.
 * This is my first PHP adventure, and my first WordPress plugin.

Viewing 2 replies - 1 through 2 (of 2 total)

 *  Thread Starter [theiconoclast31](https://wordpress.org/support/users/theiconoclast31/)
 * (@theiconoclast31)
 * [18 years, 11 months ago](https://wordpress.org/support/topic/attachments-corresponding-posts-id-gt-php-variable/#post-586292)
 * Okay, I’ve made some progress, and I can get the GUID of the attachment. With
   the GUID, can I get the post_parent (by querying the database)? I’m currently
   trying:
 * `$thisPostID = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE guid
   ='$thisGUID'");`
 * But I keep getting `Fatal error: Call to a member function on a non-object`.
 *  [craigtrader](https://wordpress.org/support/users/craigtrader/)
 * (@craigtrader)
 * [18 years, 9 months ago](https://wordpress.org/support/topic/attachments-corresponding-posts-id-gt-php-variable/#post-586357)
 * You need to declare $wpdb as a global in your function:
 * `global $wpdb;`

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Attachment’s corresponding post’s ID –> PHP Variable?’ is closed to new
replies.

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 2 replies
 * 2 participants
 * Last reply from: [craigtrader](https://wordpress.org/support/users/craigtrader/)
 * Last activity: [18 years, 9 months ago](https://wordpress.org/support/topic/attachments-corresponding-posts-id-gt-php-variable/#post-586357)
 * Status: resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
