I'm trying to loop through the fields of ACF to display all the images of a post type and a specific category
I give a practical example: I have an ACF image field (image_of_project) and I want to view all the images uploaded in a post type (projects) associated with XYZ category
Now I created this loop:
'
$loop = new WP_Query( array(
'post_type' => 'projects',
'posts_per_page' => 9,
) );
while ( $loop->have_posts() ) : $loop->the_post();
$images = get_field('image_of_project');
if( $images ): ?>
<?php foreach( $images as $image ): ?>
<div class="item">
<a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
<?php echo wp_get_attachment_image( $image ); ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php endwhile; ?>
'
The images are displayed but I do not understand why it duplicates me every single image and does not show me only the images of linked to a specific category.
Thanks to anyone who will help me on this mission!
For those interested in the feature, here’s how it worked for me.
function.php
// Loop Gallery Cat1
function my_custom_gallery_cat1() {
query_posts(array(
'post_type' => 'gd_project',
'orderby' => 'rand',
'posts_per_page' => 10,
'tax_query' => array(
array (
'taxonomy' => 'gd_projectcategory',
'field' => 'slug',
'terms' => 'example-terms',
)
),
));
?> <div class="masonry">
<?php
while (have_posts()) : the_post();
$image_field = get_field('image');
$image_url = $image_field['url'];
$image_alt = $image_field['alt']; ?>
<div class="grid-item">
<a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
<img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($image_alt); ?>" />
<h4><?php the_field( 'title' ); ?></h4>
</a>
</div>
<?php endwhile; ?>
</div> <?php
}
add_shortcode('example-terms', 'my_custom_gallery_cat1');
single-example.php
<div class="container-fluid">
<div class="row">
<?php echo do_shortcode('[categoria]');?>
</div>
</div>