Customizing WordPress Search Results to Sort by Title - Use WordPress Query.php for customized search results (
Page 3 of 5 )
Now that we understand the basic functionality of WordPress search, we can tweak this file. As with any programming task, you should back up the original query.php in your hard disk. This way, if something goes wrong, you still have the original file.
Let’s have an actual example. Suppose we would like WordPress to sort by post titles in ascending order.
We will replace (in bold):
if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
$q['order'] = 'ASC';
and
$q['orderby'] = "$wpdb->posts. post_title
".$q['order'];
The complete source code to be altered:
////////////////////////////////////////////////////////
if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
$q['order'] = 'ASC';
// Order by
if ( empty($q['orderby']) ) {
$q['orderby'] = "$wpdb->posts.post_title ".$q['order'];
} else {
// Used to filter values
$allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand');
$q['orderby'] = urldecode($q['orderby']);
$q['orderby'] = addslashes_gpc($q['orderby']);
$orderby_array = explode(' ',$q['orderby']);
if ( empty($orderby_array) )
$orderby_array[] = $q['orderby'];
$q['orderby'] = '';
for ($i = 0; $i < count($orderby_array); $i++) {
// Only allow certain values for safety
$orderby = $orderby_array[$i];
switch ($orderby) {
case 'menu_order':
break;
case 'ID':
$orderby = "$wpdb->posts.ID";
break;
case 'rand':
$orderby = 'RAND()';
break;
default:
$orderby = "$wpdb->posts.post_" . $orderby;
}
if ( in_array($orderby_array[$i], $allowed_keys) )
$q['orderby'] .= (($i == 0) ? '' : ',') . $orderby;
}
// append ASC or DESC at the end
if ( !empty($q['orderby']))
$q['orderby'] .= " {$q['order']}";
if ( empty($q['orderby']) )
$q['orderby'] = "$wpdb->posts.post_title ".$q['order'];
}
////////////////////////////////////////////////////////
Remember to back up your query.php file before finding this piece of code in the file and replacing it with the above tweaks.