Customizing WordPress Search Results to Sort by Title

Sorting search results by post title in WordPress is often useful, if your website needs its entries to be sorted alphabetically. As a quick background, WordPress is the most popular open source, free blogging/CMS platform. However, the default search results are sorted by date, so there is no easy way to sort them alphabetically except to edit the core WordPress search functionally source code.

There are a number of applications for which it would be useful to sort post titles alphabetically. For example, say you use WordPress for a social networking site. With that kind of site, people stop by and register their names. As a result, users need to be able to search for names in the WordPress search box. So the search results need to be sorted alphabetically so that visitors can easily find people’s names.

There are countless applications for the ability to sort post titles alphabetically in WordPress. Here’s another example: say you use WordPress on an online bookstore. Again, you’ll need to alphabetize search results, by book titles and/or author names. As of February 2009, surprisingly enough, no WordPress plug-in has been developed to provide this feature.

In fact, one of the best ways to apply this feature is to work with the “Search Everything” plug-in. You can read more about this in: http://wordpress.org/extend/plugins/search-everything/ . A detailed discussion of this plug-in is beyond the scope of this article; however, sample applications are illustrated in the last section of this tutorial.

It is the objective of this article to explain how to sort WordPress search results by post title.

Basic Requirements and Enabling WordPress Search Widget

This tutorial has been tested to work in WordPress version 2.5.1 to 2.6.1. To tweak the WordPress search function appropriately, you need to have the following:  

  • Full FTP access to your WordPress site.
  • A newer version of WordPress, specifically 2.5.1 to 2.7 (older versions of WordPress have not been tested for this application, and it is recommended that you upgrade for security reasons).

The tweak will not work if you do not have full FTP access and the appropriate version of WordPress. You may need to coordinate with your web agency or any person that has full access to the website server files.

If you have all of the requirements, the next thing you need to do is enable the WordPress Search Widget. The steps below have been tested to work in WordPress version 2.5.1 to 2.6.1.

1. Go to Dashboard

2. Go to Design

3. In the list of sub-menus, namely Themes, Widgets and Theme Editor, click “Widgets”

4. In the first column, you will see “Available Widgets.” Find “Search” and then click “Add.” This will add a search form to your website.

After completing these steps, the search widget will now be shown in the “current widgets” column. Check the screen shot below for an example:

{mospagebreak title=The WordPress Search Results Function}

By default, WordPress post titles are sorted by the date they were published. This means that if you have thousands of WordPress posts that contain “tips” in the title tag, and you search for "tips" in the WordPress search box, the ones that will be shown at the top of the results are the most recent articles.

All search queries from WordPress search forms are handled by a special WordPress file called “query.php.” This can be found in the wp-includes folder in WordPress’s FTP files.

In this PHP file (query.php), the most important section in the source code is this one:

///////////////////////////////////////////

if ( empty($q['order']) || ((strtoupper($q['order']) != ‘ASC’) && (strtoupper($q['order']) != ‘DESC’)) )

$q['order'] = ‘DESC';

// Order by

if ( empty($q['orderby']) ) {

$q['orderby'] = "$wpdb->posts.post_date ".$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_date ".$q['order'];

}

///////////////////////////////////////////////////////

This is where WordPress will know whether the search results will be sorted by post date or other parameters. This is the section where the results will be sorted, whether in descending or ascending order.

Specifically (in bold):

if ( empty($q['order']) || ((strtoupper($q['order']) != ‘ASC’) && (strtoupper($q['order']) != ‘DESC’)) )

  $q['order'] = ‘DESC';

is responsible for a descending post publishing date order in the default search results; that is, the most recent post should be shown at the top of the search results list.

$q['orderby'] = "$wpdb->posts. post_date ".$q['order'];

This piece of code shows that the search results will be based on “post_date.”

{mospagebreak title=Use WordPress Query.php for customized search results}

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.

{mospagebreak title=Sort Search Results by Title Plug-in}

Sometimes it is easier not to edit the WordPress core files such as query.php, and just use WordPress plug-in features for this. This is a more convenient approach, since we only need to upload a PHP file to a /wp-content/plugins/ directory in your FTP server. Then activate the plug-in to enable the feature.

To do this, we need a PHP file. Below is the source code,

<?php

add_action(‘pre_get_posts’,’sort_searchresult_by_title’);

function sort_searchresult_by_title($k) {

if(is_search()) {

$k->query_vars['orderby'] = ‘title';

$k->query_vars['order'] = ‘DESC';

}

}

?>

This plug-in works by adding actions (from the plug-in) to WordPress’s existing search functions. This is indicated by add_action

The PHP function sort_searchresult_by_title($k) will perform the actual sorting. This will communicate with WordPress’s MySQL database to pick up post titles and then sort them by “descending” order as specified by:

$k->query_vars['order'] = ‘DESC';

To download the plug-in, visit the following URL: http://blog.360.yahoo.com/blog-nNv5JKEydKKD9OmfLBfY?p=2

{mospagebreak title=Designing a Complex Application}

As said earlier, this functionality can be used to create complex applications in WordPress. For example, say you need to create a music site that will enable users to rate a song from 1 to 5. There are also other users that might be looking for great songs in your catalog.

The following are example title tags (dynamically generated as the average song rating) of the song post. Assume all of them use “rock-music” as the custom fields in the post (combine with http://wordpress.org/extend/plugins/search-everything/ , so that WordPress will look at custom field data as a basis for the search).

Song rating 4.5 “ Song title 1”

Song rating 3.2 “ Song title 2”

Song rating 4.9 “Song title 3”

If a user types into the search box the phrase “rock music,” WordPress will then return the search results in the descending order of song ratings, so that listeners will be able to listen the best songs first:

Song rating 4.9 “Song title 3”

Song rating 4.5 “ Song title 1”

Song rating 3.2 “ Song title 2”

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan