I have a list of terms showing in slug order but I need to order them by most recent posts, so it will be changing depending on what term has the most recent entries... Is there a way to do so? I tried the solution proposed here: Retrieve taxonomy terms in order of their post's date?
But it is showing the terms in date of term creation, not the date of the most recent posts.
My code:
function wpse147412_order_terms_by_post_date( $pieces, $taxonomies, $args ) {
global $wpdb;
if ( 'post_date' !== $args['orderby'] ) {
return $pieces;
}
$args = wp_parse_args( $args, array( 'post_types' => 'episode' ) );
$pieces['fields'] = 'DISTINCT ' . $pieces['fields'];
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id";
$pieces['join'] .= " JOIN $wpdb->posts AS p ON p.ID = tr.object_id";
$pieces['where'] .= " AND p.post_type IN ('" . implode( "', '", (array) $args['post_types'] ) . "')";
$pieces['orderby'] = 'ORDER BY p.post_date';
return $pieces;
}
add_filter( 'terms_clauses', 'wpse147412_order_terms_by_post_date', 10, 3 );
Placed above in functions, then in the page I need the terms:
<?php
$tax_terms = get_terms( 'series',
array( 'post_types' => 'episode',
'orderby' => 'post_date',
'order' => 'DESC' )
);
if( is_array( $tax_terms ) && count( $tax_terms ) > 0 ):
foreach ($tax_terms as $tax_term):
?>
<div class="series-button text-center">
<a href="<?php echo esc_attr(get_term_link($tax_term, $taxonomy));?>">
<figure class="align-items-center d-flex" style="background-image: url('<?php echo z_taxonomy_image_url($tax_term->term_id, 'series-img'); ?>');">
<h3 class="text-center uppercase"><?php echo $tax_term->name; ?></h3>
</figure>
</a>
</div>
<?php
endforeach;
endif;
?>