Last active
January 15, 2018 03:27
-
-
Save xnau/b163a7c84d294e91c360de324fdc7c3c to your computer and use it in GitHub Desktop.
Demonstrates how to sort by a Participants Database list of month values...or any arbitrary list of values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: PDB Sort By Month | |
* Description: Demonstrates how to set up an arbitrary list sort in Participants Database | |
*/ | |
/* | |
* Important: this assumes that the column you want to put the arbitrary sort on is already | |
* present in the sort as defined in the shortcode. For instance, in this example, the shortcode | |
* should have the sort set up like this: [pdb_list orderby="month" order="ASC"] then that sort | |
* gets replaced by the one we are setting up in this filter. | |
* | |
*/ | |
add_filter( 'pdb-list_query', 'xnau_sort_by_month' ); | |
/** | |
* sorts the list by the value of the month column | |
* | |
* @param string $query the current list query | |
*/ | |
function xnau_sort_by_month( $query ) | |
{ | |
// this is the name of column you want to sort by | |
$sort_field = 'month'; | |
// this is the list of values that determines the sort | |
// these values must match exactly values that will be found in the record | |
$sort = "'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'"; | |
// set up our patterns | |
$pattern = '/(ORDER BY .*?)(p\.' . $sort_field . ')/'; | |
$sort_pattern = '\1 FIELD( p.' . $sort_field . ', ' . $sort . ') '; | |
if ( preg_match( $pattern, $query ) ) { | |
// this replaces the standard sort with our arbitrary sort | |
$query = preg_replace($pattern, $sort_pattern, $query ); | |
} | |
return $query; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just learned you can reverse the order by changing the "order" attribute in the shortcode to DESC.