Home › Forums › General Issues › Sort by post category and then by date › Reply To: Sort by post category and then by date
Great, thanks!
This is how it was solved.
<?php
$allPosts = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'intervention',
'orderby' => 'meta_value',
'meta_key' => 'publication_category',
'order' => 'ASC'
));
// Get the posts
$posts = $allPosts->posts;
// Define custom sorting function
function custom_sort($a, $b) {
// First, compare by publication category
$categoryA = strtolower(get_post_meta($a->ID, 'publication_category', true));
$categoryB = strtolower(get_post_meta($b->ID, 'publication_category', true));
// Compare categories alphabetically
$categoryComparison = strcmp($categoryA, $categoryB);
// If categories are the same, compare by publication year
if ($categoryComparison == 0) {
$yearA = intval(get_post_meta($a->ID, 'year', true));
$yearB = intval(get_post_meta($b->ID, 'year', true));
return $yearB - $yearA;
}
return $categoryComparison;
}
// Sort the posts array using the custom sorting function
usort($posts, 'custom_sort');
foreach ($posts as $post) {
setup_postdata($post);
//Display posts ordered by category and inside categories organise by dates
// Reset post data
wp_reset_postdata();
?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.