I’ve found a hack that I don’t love. @billerickson – if there is a better way to do this (there must be), please let me know.
My hack:
I found this tutorial (Reversed Ordered List – Display Posts) which I thought would solve my problem (if I switched from wrapper="div" to wrapper="ol"), so I switched to ol, added the filter, and verified that the filter was getting called and setting the reversed attribute on the ol … but no change!
Did a bit of reading up on what the reversed attribute actually does, and it seems that it reverses the numbering of an ordered list, but not the actual order of the items, ha!
Then, however, I found that the ordering of items in a flex control can be reversed using flex-direction: row-reverse. Since I already use flex (among other things) on my display-posts-listing style, I added the following CSS, which only kicks in when the tutorial filter has added the reversed attribute.
ol[reversed].display-posts-listing {
flex-direction: row-reverse;
}
/* existing dps style */
.display-posts-listing {
padding: 0 0 1em 0; /* t r b l */
list-style: none;
display: flex;
align-items: stretch;
flex-wrap: wrap;
justify-content: center;
gap: .5em;
}This does require me to use ol as my wrapper instead of div, which feels wrong, but given how I style everything anyway, seems to not change the layout (with the exception of reversing the display order, as I wanted).
I spoke too soon. My hack works well when the items in the flex container can be contained on a single row, but as soon as they wrap, each row is “row-reversed” independently, so the sort order gets extra wonky.
So, I’m back to no solution at all. I’m wondering if the best solution is to use a filter to re-order the items during HTML generation?
That’s an interesting request! It took me a bit of digging to figure out a solution.
First, add an attribute to your shortcode, like [display-posts reverse="true"]
Then, use the display_posts_shortcode_args filter to check for that attribute, and if present, add an attribute to the query args.
Finally, use the posts_results filter in WP core to check for your custom attribute, and if present, reverse the post listing using array_reverse.
Here’s the full code:
// look for reverse="true" and add an attribue to WP_Query
add_filter( 'display_posts_shortcode_args', function( $args, $original_atts ) {
if ( isset( $original_atts['reverse'] ) && filter_var( $original_atts['reverse'], FILTER_VALIDATE_BOOLEAN ) ) {
$args['dps_reverse'] = true;
}
return $args;
}, 10 , 2 );
// once the posts have been retrieved, check for that attribute and reverse them
add_filter( 'posts_results', function ( $posts, $query ) {
if ( isset( $query->query['dps_reverse'] ) ) {
$posts = array_reverse( $posts );
}
return $posts;
}, 10, 2 );-
This reply was modified 2 minutes ago by
Bill Erickson. Reason: remove inaccurate inline comments
