Support

Account

Home Forums ACF PRO Custom loop in ACF block

Helping

Custom loop in ACF block

  • Hello,

    I’m creating a block to display a “workshop” custom post type
    Each post has a date custom field and I would like to sort them by date

    But I can’t get the value of the field in the block render template with a regular WP loop… I tried a query_post and it’s working but then I can’t sort the results by the date field 🙁

    here is my code so far, what am I missing… I guess I have to make a second loop to get the post by my date custom field… but can’t find out how!

    					<?php
    						$num = get_field('number');
    						$cat = get_field('cat');
    						//$date = get_field('date');
    						
    						if ($num) {
    							$number = $num;
    						} else {
    							$number = '-1';
    						}
    						
    						// if ($date) {
    						// 	$key = 'date';
    						// 	$by = 'meta_value';
    						// } else {
    						// 	$key = null;
    						// 	$by = null;
    						// }
    						
    						$args = array(
    							'posts_per_page' 	=> $number,
    							'post_type' 		=> 'product',
    							//'meta_key'			=> $key,
    							//'orderby'			=> $by,
    							'order'				=> 'DESC',
    							'tax_query' => array(
    								array(
    									'taxonomy' => 'product_cat',
    									'terms' => $cat,
    									'field' => 'slug',
    								),
    							),
    						);
    						//$products = new WP_Query($args);
    						$products = query_posts($args);
    						
    						foreach ($products as $p) : 
    						
    							$date = get_field('date', $p->ID);
    							
    					?>
    						<div class="product-block">
    							
    							<div class="product-figure">
    								<?php echo get_the_post_thumbnail($p->ID, 'screen-md' ); ?>
    							</div>
    							<p class="product-title h3-like"><?php echo get_the_title($p->ID); ?></p>
    							<p><?php echo $date; ?></p>
    							
    						</div>						
    							
    					<?php 
    						endforeach;
    						wp_reset_postdata();
    					?>	
  • Hey @anybodesign

    You should able to do that via get_posts() too.

    The most problem you don’t use the proper order value for that.
    I think you want to change the ‘order’ like this:

    $posts = get_posts([
    	'post_type'		=> 'product',
    	...
    	'meta_key'      => 'your_date_field',
      	'orderby'       => 'meta_value_num',
    ]);

    The key is the meta_value_num when you order by number / date type of fields

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.