Now this is an issue I encountered while designing some WordPress themes: posts and specifically pages don’t display in real date order. I still can’t precisely tell why this is happening, but it does, and it actually bothers me a bit since most of my websites use a precise page hierarchy. So here we go, short analyse and my personal solution.
Classic WordPress usage
WordPress provides simple functions to get pages/posts, and an easy way to order them by passing parameters through the functions. You can use get_posts
or, in my case, get_pages
; get_posts
uses orderby
(all available values here), get_pages
uses sort_column
(all available values here). You’d expect the following example to list you all your published pages ordered by date, latest first:
$pages = get_pages( array( 'post_type' => 'page', 'post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'DESC' ) );
Well, that works great for me, as long as I don’t ever modify again one single page after I published it. If I edit a page, then post_modified
is set to a new date, and that page will appear as the latest published… Which can be quite annoying.
I spent a couple of hours browsing the web, reading docs and trying to find why this is happening, not a clue up to now, be welcome to enlighten me if you have one! Still, I ended with a homemade solution: a little custom function to reorder my pages properly.
function sort_pages_by_realdate()
We just have to add this to our theme’s functions.php
:
function sort_date( $a, $b ) { $a_date = strtotime( $a->post_date ); $b_date = strtotime( $b->post_date ); if ( $a_date == $b_date ) return 0; return ( $a_date < $b_date ) ? -1 : 1; } function sort_pages_by_realdate( $pages ) { usort( $pages, 'sort_date' ); krsort( $pages); return $pages; }
Our first example now become:
$pages = get_pages( array( 'post_type' => 'page', 'post_status' => 'publish', 'sort_column' => 'post_date', 'sort_order' => 'DESC' ) ); $pages = sort_pages_by_date( $pages );
That’s it 🙂 The important point is to use the posts’ timestamps to compare, not merely post_date
. Also note that using krsort()
is not an obligation; it depends of the pages order you want. usort
will leave you a table ordered from the most ancient pages to the most recent; I use krsort()
to reverse the array because I want the latest page by date to be the first listed, so don’t use it if you don’t want that specific order.