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

Unfortunately, $post->post_parent is a single variable and not an array. I want to get all post_parents of a post (especially of an attachment, which is often linked to multiple posts!).

share|improve this question

You clearly refer to this function which is used like this :

global $post;
$parents = get_post_ancestors( $post->ID );
share|improve this answer
Looks good. I tried this out but why does it output only "Array"? The attachment got multiple ancestors of course. $attachment = get_post($file_id); echo get_post_ancestors( $attachment ); – luke Jul 10 '13 at 19:36
there are multiple values to return – JMau Jul 10 '13 at 19:55
But they aren't showing up, the array is empty. – luke Jul 10 '13 at 19:57
Means there are no ancestor. You need to target attachments in this case. So you can use a get_posts() to get only attachments and then retrieve ancestors. – JMau Jul 10 '13 at 20:05
why can't i use a specific "post"/attachment like in my example? – luke Jul 10 '13 at 20:22

This function gives the list of post ids to which attachment attach.

Paste this code in functions.php

 * get_attachment_parent fx gives array of post id to which given attachment attach
 * @param  [int $att_id attachment id
 * @return array        list of post ids
function ravs_get_attachment_parent( $att_id ){

        'posts_per_page'  => -1,


    if( ! $posts && empty($posts) )
            return array();

    $ancestors = array();

    foreach ($posts as $post) {
        $attachment = get_post_thumbnail_id($post->ID);
        if( $att_id === $attachment  && ! in_array($post->ID, $ancestors))
            $ancestors[] = $post->ID;
    return $ancestors;

and access this function in loop

if( has_post_thumbnail() )
 print_r( ravs_get_attachment_parent( get_post_thumbnail_id(get_the_ID())) );

or outside loop

print_r( ravs_get_attachment_parent( $attachment_id );
share|improve this answer
thanks this helped me a lot :-) i adapted it so it can now handle with attachments which are attached to multiple posts but also with multiple attachments attached to one post. see this: codepad.org/GmNh7M9e – luke Jul 11 '13 at 10:34
up vote 0 down vote accepted

Based on @Ravs solution I worked this out. This function returns all parent posts, and it checks all attachments attached to all posts.

See this: http://codepad.org/GmNh7M9e

share|improve this answer

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.