I’m using get_pages() function to get all subpages from a page like this:
$childrens = get_pages(array('child_of' => 7,
'sort_column' => 'post_date',
'sort_order' => 'DESC',
'depth' => -1));
This is supossed to get me a list of all pages (no matter if direct children, children of children, etc) orderen by the date they were created, but instead its showing me the list of pages in a strange order, here’s the output when I run a foreach on the $childrens array and output the post_date on each:
2011-05-10 15:37:03
2011-05-10 15:35:59
2011-05-10 15:01:18
2011-05-10 17:12:32
2011-05-10 15:00:47
2011-05-10 14:00:14
2011-05-11 04:19:08
2011-05-10 23:52:54
2011-05-10 15:20:12
2011-05-10 15:05:10
As you can see they’re not ordered by date descending, I tried using other options in the sort_column key but none seemed to e working correctly, does anyone know what could be wrong?
Thanks in advance!
This is indeed an error, and probably caused by the
child_of
argument.Because
child_of
requests the whole subtree of the given page (not only the direct children, but also children of those children and so on), WordPress first queries for all the pages and then selects a subset of those pages. The first query respects the order, but the second subselection messes this up by just usingarray_merge()
.I have created a Trac ticket for this.
after looking around a bit I managed it to make it work using the following:
I’m using the usort function to sort the array by the objects’ date, and the reversing it to get it ordered from newest to oldest, thanks all for pointing me in the right direction I voted all you guys up.
Im not sure how to remedy the problem with WordPress – im getting the same results as you are, but this can be achieved using the PHP functions
sort()
andrsort()
and a little bit of dirty work usingforeach
.rsort()
would sort an array in reverse order andsort()
from lowest to highest.Try this:
Some sidenotes while searching for a solution:
get_posts()
arguments.Questions:
'include'
as argument? This sets'child_of'
to zero.Try this and tell me about the result you get. Maybe you can re-order them there until you got a satisfying solution:
Edit
Here you got a set of functions that help you working around until the patch has gone into a wp release:
use get_children instead – replace child_of with post_parent / sort_column / sort_order – ie.: