I had a recent request for the ability to order sermon terms by the start date of the sermon series.
In this tutorial I will show you how to order get_terms() based on a custom field.
In this case, I’m using an Advanced Custom Fields Date field for the date and assigned it.
The short version of this is to get the terms using get_terms() then build an array that includes the start date and term object.
We can then sort the array via ksort or krsort and output as needed with a foreach loop.
<?php | |
// Get terms - replace "SERMON" with your term | |
$terms = get_terms('SERMON'); | |
// Set an empty array | |
$sermon_series = array(); | |
// Loop through terms and build our array | |
foreach ( $terms as $term ) { | |
// Advanced Custom Fields Date field | |
$sermon_series_date = get_field( 'sermon_series_date', $term ); | |
$sermon_series[$sermon_series_date] = $term; | |
} | |
// Sort the terms by date | |
krsort( $sermon_series, SORT_NUMERIC ); | |
// This will build the terms as cards | |
// I also has a custom field being used for category image | |
foreach ( $sermon_series as $sermon_series_date => $term ) { | |
$term_id = $term->term_id; | |
$image_id = get_field('sermon_category_image', $term); | |
$image = wp_get_attachment_image($image_id, 'sermon-card'); | |
$intro_text = $term->meta[intro_text]; | |
$term_link = get_term_link( $term ); | |
?> | |
<div class="card"> | |
<a href="<?php echo $term_link; ?>"><?php echo $image ?></a> | |
<div class="card-content"> | |
<div class="title-wrap"> | |
<h3><a href="<?php echo $term_link; ?>"><?php echo $term->name; ?></a></h3> | |
</div> | |
<p><?php echo $intro_text ?></p> | |
<a class="read-more" href="<?php echo $term_link; ?>">View Sermons</a> | |
</div> | |
</div> | |
<?php } ?> |