WordPress Snippets at WPcustoms

List all attachments from custom post type

Sometimes you need to get all attachments (i.e. from a portfolio custom post type) and list them on a specific page template. This function calls all post ids from the CPT and loops through the attachments. A great snippet start to build a portfolio overview page and link to the portfolio posts with some modifications.


/**
 * Snippet Name: List all attachments from custom post type
 * Snippet URL: https://wpcustoms.net/snippets/list-attachments-custom-post-type/
 */
  function wpc_list_cpt_attachments() {
    $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 .= '';

          echo $output;
      }

    }
}