I am also trying to sort by a custom field (end_date) that I created and am new to PHP. I would need something similar to ellebeaux. I want to sort all posts on all pages by end_date. It might even be the same hook mentioned above. Thanks for help since I’m a newbie!
If it’s not that simple, I might try using the old unsupported version first.
I found the easiest way to modify the sort characteristics is to use the hook “posts_pieces” which provides access to all the pieces of the SQL statement used in wp_query.
Depending on your theme, you need to change the statement only if it applies to your specific case (the hook is called all over the place by widgets, pages, etc). I am using weaver ii and the page template ‘pages with posts’; I set the ‘order posts’ to ‘rand’ so I can recognize my case uniquely. Here is the nano plug-in code:
if ($pieces['orderby'] == 'RAND() DESC') { // only modify pages where 'rand' specified
$curDate = date("Y-m-d");
$pieces['fields'] .= ", mv_postmeta.*";
$pieces['join'] .= " JOIN mv_postmeta ON (mv_posts.ID = mv_postmeta.post_id AND mv_postmeta.meta_key IN ('startDate', 'endDate')) ";
$pieces['where'] .= " AND (mv_postmeta.meta_key = 'endDate' AND mv_postmeta.meta_value > '$curDate') ";
$pieces['orderby'] = "mv_postmeta.meta_value ASC";
}
return $pieces;