WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Making a loop of attachments, using post__in array? (2 posts)

  1. SpankMarvin
    Member
    Posted 3 years ago #

    Hi there

    I am creating a new instance of the WP_Query class to create a simple custom loop of attachments. the idea is that the administrator can add an array of custom fields that refer to media attachments as resources. So, they would enter "Resource ID" and the value would be the ID number of the upload.

    So far so good. The loop works just fine when I specify in my arguments array (which I'm passing into my class call) and have ONE attachment called by using p => $att_id

    I would like to insert an array instead for attachment ids, so am using post__in. Here is my code, but once I do it this way, nothing happens.

    $resources = get_post_meta($id, "Resource ID", false); // Allow more than one resource; returns an array
    $content = '';
    
    if($resources){
    	$att_ids = array();
    	foreach($resources as $resource){
    		$resource = trim($resource);
    		$att_ids[] = $resource;
    	}
    	$args = array(
    		'post_type' => 'attachment',
    		'posts_per_page' => -1,
    		'post__in' => $att_ids
    	);
    
    	$att_query = new WP_Query($args);
    	if( $att_query->have_posts() ):
    	while( $att_query->have_posts() ): $att_query->the_post();
    			$content .= 'Blah blah blah';
    		endwhile;
    
    		endif;
    // etc. etc.

    Any guidance gratefully received!

    John

  2. SpankMarvin
    Member
    Posted 3 years ago #

    Ok, I sorted it by using get_posts instead and that allowed me to pass multiple ids with the include parameter. In case anyone has come here searching for something similar, my revised code is as follows, and returns simply the list of attachment titles:

    if($resources){
    
    	$att_ids = array();
    	foreach($resources as $resource){
    		$resource = trim($resource);
    		$att_ids[] = $resource;
    	}
    	$att_ids = implode(',',$att_ids);
    
    	$args = array(
    		'post_type' => 'attachment',
    		'posts_per_page' => -1,
    		'include' => $att_ids
    	);
    
    	$atts = get_posts($args);
    	if($atts){
    	$content .= '<div class="resources-container resource">
    	<ul>';
    		foreach($atts as $att){
    		$content .= '<li>'.$att->post_title.'</li>';
    	}
    	$content .= '</ul>
    	</div>';
    	}

Topic Closed

This topic has been closed to new replies.

About this Topic