0

Trying to get the attachment file url for current post, using this code:

if ( is_singular('post') ) {
    $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => $post->ID );
    $attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
          echo wp_get_attachment_url( $attachment->ID ); 
        }
    }
    else {
}
    }

the problem is: this code displays the url of a file attached to another post 'author' which is a child post in relationship by ACF advanced custom fields plugin. I need to display the url of the file attached to current post and not to the child one. any suggestions please?

1

try get_pages with

'child_of' => get_the_ID(),
'parent' => get_the_ID(),

If you need i can post full code

EDIT :

if ( is_singular('post') ) {
    $args = array( 
        'post_type' => 'attachment',
        'posts_per_page' => -1, 
        'post_status' => null, 
        'parent' => $post->ID ,
        'child_of' => $post->ID,
        'sort_order' => 'desc'
    );
    $attachments = get_pages( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            echo wp_get_attachment_url( $attachment->ID ); 
        }
    }else {
    }
}

I hope this code help you

7
  • Thanks a lot for replying. yes please if you can write the full code. – nisr Aug 26 '15 at 21:16
  • I already edit my post and write full code .. – Khaled Sadek Aug 26 '15 at 21:26
  • this displays all the urls of all the files attached to the parent and the child posts. is there any way to display only those of parent post? – nisr Aug 26 '15 at 21:32
  • So soory , this's my mistake .. I use get_posts not get_pages.. try now with my edit get_pages – Khaled Sadek Aug 26 '15 at 21:46
  • 1
    thanks @Kika your answers helped me figure out the solution – nisr Aug 28 '15 at 11:11

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.