I’m trying to get the attachments of a specific term (in its archive page). But the results are showing the resulting images 5 times instead of one.
I have multiple loops in this page – one to show related posts, another to show related products (custom post), and this one to show related images. Custom posts and posts are working nicely, but I can’t show the attachments in the right way. :S
<?php $queried_object = get_queried_object();
$term_id = $queried_object->term_id;
$args = array(
'post_status' => 'inherit',
'numberposts' => 0,
'post__not_in' => array_merge($do_not_duplicate,get_option( 'sticky_posts' )),
'post_type' => 'attachment',
);
$args['tax_query'] = array(
array(
'taxonomy' => 't-arte',
'terms' => $term_id,
'field' => 'id',
),
); ?>
<?php $t = $data['t-arte'];
$array = explode(" ", $t);
$array = array_unique($array);?>
<?php $media_query = array_unique($array); ?>
<?php $media_query = get_posts($args);
if( !empty( $media_query ) ) :
foreach ($media_query as $media_query) :
global $post; $post = $media_query;
setup_postdata($media_query);
?>
<div id="archivespage-media-item">
<?php $attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<div id="imagem">';
the_attachment_link( $attachment->ID, true );
echo '</div>';
}
}?>
</div>
<?php endforeach;else :?>
<p>Ainda não temos nenhuma imagem relacionada :(</p>
</div>
<?php endif; ?>
<?php wp_reset_query();?>
I think the problem is that you’re passing the wrong arguments to the
$attachments
query, causing you not to get the intended posts in the$attachments
query.Here’s what you’re doing:
So, you’re querying all posts that are post-type
attachment
, rather than only the posts that are attached to the current post being looped through in$media_query
.Here’s how you loop through
$media_query
:(Note: bad form. Try something like
foreach ( $media_query as $media ) :
instead.)You need to pass the ID of the current post to your
$attachments
query, aspost_parent
. Something simple might be:I got it! The result will show all attachments in a specific term inside term’s archive page. Thanks Chip!