Skip to content

Instantly share code, notes, and snippets.

@greghunt
Last active March 12, 2018 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghunt/a5e9fef8f7913d3cd49c3b9c1dce7495 to your computer and use it in GitHub Desktop.
Save greghunt/a5e9fef8f7913d3cd49c3b9c1dce7495 to your computer and use it in GitHub Desktop.
Add GET based filtering of WordPress queries.
<?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 );
}
});
@greghunt
Copy link
Author

greghunt commented Mar 12, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment