Support

Account

Home Forums General Issues Sorting by 2 acf fields, date and time problem

Solved

Sorting by 2 acf fields, date and time problem

  • Hi,

    Any idea why my wp_query doesn’t work like it should ?
    It should order posts by date and time. For now it works only for dates. Instead of “start_at” it orders by post creation time.

    <?php // Meta query for tab
    $current_date = date('Ymd');
    $future_date = date('Ymd', strtotime('+6 days'));

    $args = [
    'post_type' => 'events',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'order' => 'ASC',
    'meta_query' => [
    [
    'key' => 'event_date',
    'value' => [$current_date, $future_date], // Use an array to specify a range
    'compare' => 'BETWEEN', // Use BETWEEN to specify a range
    'type' => 'DATE'
    ],
    [
    'key' => 'start_at',
    'compare' => 'EXISTS' // Include this line to ensure 'start_at' meta field exists
    ]
    ],
    'orderby' => [
    'event_date' => 'ASC', // Order by 'event_date' in ascending order
    'start_at' => 'ASC', // Then order by 'start_at' in ascending order
    'meta_type' => 'TIME' // Specify meta_type as 'TIME' to correctly order by time format
    ]
    ];

    include(locate_template('template-parts/tabs-inner-include.php', false, false));
    ?>

  • Ok I sorted it out myself. You need to use named meta query.

    <?php // Meta query for tab
    	$current_date = date('Ymd');
    	$future_date = date('Ymd', strtotime('+6 days'));
    
    	$args = [
    	    'post_type' => 'events',
    	    'post_status' => 'publish',
    	    'posts_per_page' => 12,
    	    'meta_query' => array(
            'relation' => 'AND',
    	        'date_meta' => array(
    	           	'key' => 'event_date',
    	            'value' => [$current_date, $future_date], // Use an array to specify a range
    	            'compare' => 'BETWEEN', // Use BETWEEN to specify a range
    	            'type' => 'DATE',
    	        ),
    	        'time_meta' => array(
    	            'key' => 'start_at', // 'start_at' is the custom field storing the time value
    	            'type' => 'TIME' // Use 'TIME' meta type for 'start_at' field
    	        ),
    	    ),
    	    'orderby' => [
    	        'date_meta' => 'ASC', // Order by 'event_date' in ascending order
    	        'time_meta' => 'ASC' // Then order by 'start_at' in ascending order
    	    ]
    	];
    
    	include(locate_template('template-parts/tabs-inner-include.php', false, false));
    ?>
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.