Support

Account

Home Forums Front-end Issues Loop posts by ACF custom field (post ID)

Helping

Loop posts by ACF custom field (post ID)

  • I’m new to ACF, and having some trouble which I hope somebody is able to help with. I have a series of posts (Stories) which contain a carousel that loops through the post type ‘testimonials’ within their page template.

    I want to set it up so that any particular Story has the ability to display specific testimonials by their IDs. If no ID(s) are specified, it will display all the testimonials.
    So I have crated a custom field for each Story (define_testimonials), where you can enter testimonial ID(s) (e.g. 12,53,224,232). If no ID(s) are entered, it should display all.

    So in summary I want to create a loop which displays post type ‘testimonials’. If custom field (define_testimonials) has ID(s), display posts with this ID(s), else display all posts.

    Hopefully this makes sense – below is the code as it currently stands. Any pointers in the right direction would be hugely appreciated.

    <?php
    	$loop = new WP_Query(
    		array(
    			'post_type' => 'testimonial',
    			'posts_per_page' => 12,
    			'orderby' => 'menu_order',
    			'order' => 'ASC',
    		)
    	
    	);
    	if ( $loop->have_posts() ) :	
    ?>
    
    <section class="dark patterned padding-lg">
      <div class="wrap owl-carousel" id="testimonials-carousel">
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <div class="item">
          "
            <?php the_field('testimonial_content');?>
            "
    
          <p class="author">
            <?php the_title();?>
          
    
        </div>
        <?php  endwhile; ?>
      </div>
    </section>
    <?php endif;
    	wp_reset_query();
    ?>
    
  • Hi Marco! Take a look at this and tell me if it works

    
    <?php 
    $define_testimonials = get_field('define_testimonials');
    
    $args = array(
    	'post_type' => 'testimonial',
    	'posts_per_page' => 12,
    	'orderby' => 'menu_order',
    	'order' => 'ASC',
    );	
    
    if($define_testimonials) {
        
        // I understand the field returns the ids separated by comma so we convert the string to an array
        $array_ids_testimonials = explode(',', $define_testimonials);
    
        // pass the IDs array into post__in arg
        $args['post__in'] = $array_ids_testimonials;
    }
    
    $loop = new WP_Query($args);
    
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Loop posts by ACF custom field (post ID)’ is closed to new replies.