jehan
jehan

Reputation: 79

How to get post id from attachment wordpress

I'm using below code to get all the attachments assign to my custom post type..but now i want to get the post id within the loop..how can i do that??

$query = new WP_Query(  
          array(  
            'post_type' => 'portfolio', // adjust your custom post type name here  
            'posts_per_page' => -1,  
            'fields' => 'ids'  
          )  
        );  
        $image_query = new WP_Query(  
          array(  
            'post_type' => 'attachment',  
            'post_status' => 'inherit',  
            'post_mime_type' => 'image',  
            'posts_per_page' => -1,  
            'post_parent__in' => $query->posts,  
            'order' => 'DESC'  
          )  
        );  


        if( $image_query->have_posts() ){  
          while( $image_query->have_posts() ) {  
              $image_query->the_post();  
              $imgurl = wp_get_attachment_url( get_the_ID() );  

             if(!empty($output)) $output = 'Sorry, no attachments found.';  
              $output .= '<a href="'.$imgurl.'"><img src="'.$imgurl.'"></a>';  

              echo $output;  
          }  

Thanks!

Upvotes: 0

Views: 2514

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9951

Depending on which ID you are looking for inside the loop, you can do the following

  • $post-ID -> Returns the post ID from the attachment post being displayed

  • $post->post_parent -> Returns the current attachment post parent post ID

Upvotes: 1

Related Questions