WordPress.org

Ready to get started?Download WordPress

Forums

Get all posts with attachments (4 posts)

  1. leemon
    Member
    Posted 3 years ago #

    Hi!

    I'm using two nested loops to get all posts with one or more attachments:

    $wp_query = new WP_Query(array('post_type' => 'magazine',
                                   'paged' => $paged,
                                   'posts_per_page' => 10
                ));
    while ( have_posts() ) : the_post();
        $args = array('order' => 'ASC',
                      'post_type' => 'attachment',
      		  'post_parent' => $post->ID,
     		  'post_mime_type' => 'application/zip, application/pdf',
    );
        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
    	    echo wp_get_attachment_link($attachment->ID);
    	}
        }
    endwhile;

    I was wondering if there's a way to do the same with just one loop.

    Thanks in advance

  2. ucfknight10
    Member
    Posted 3 years ago #

    the only way i can think of doing it with one loop would be to write a custom mysql query of the db, grabbing the ids of all posts of type 'magazine', and using the mysql command 'join' to select all rows where post_parent is the id grabbed from wp_posts, post_type is attachment, post_mime_type is zip or pdf.

  3. leemon
    Member
    Posted 3 years ago #

    Thanks! I'll try this.

  4. ucfknight10
    Member
    Posted 3 years ago #

    you understand what i meant by using the mysql 'join' command?

Topic Closed

This topic has been closed to new replies.

About this Topic