Last active
March 12, 2018 14:43
-
-
Save greghunt/a5e9fef8f7913d3cd49c3b9c1dce7495 to your computer and use it in GitHub Desktop.
Add GET based filtering of WordPress queries.
This file contains hidden or 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 | |
/** | |
* Allow filtering of index/archives by GET | |
* Example) Adding ?sort=-date will sort posts descending by date. | |
* Possible Values: https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters | |
*/ | |
add_action('pre_get_posts', function ($query) { | |
if( $query->is_main_query() ) { | |
$sort = "relevance"; | |
$order = "DESC"; | |
if ( isset($_GET['sort']) ) { | |
$sort = $_GET['sort']; | |
$order = substr($sort, 0, 1); | |
if($order == "-") { | |
$order = "DESC"; | |
$sort = ltrim($sort, '-'); | |
} else { | |
$order = 'ASC'; | |
} | |
} | |
$query->set( 'orderby', $sort ); | |
$query->set( 'order', $order ); | |
} | |
}); |
Author
greghunt
commented
Mar 12, 2018
•
- Possbile Values
- Use in conjuction with this autosubmit filter for easy filter toggle.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment