Codex tools: Log in / create account
Contents |
Plugins generally extend the functionality of WordPress by adding Hooks (Actions and Filters) that change the way WordPress behaves. But sometimes a plugin needs to go beyond basic hooks by doing a custom query, and it's not as simple as just adding one filter or action to WordPress. This article describes what custom queries are, and then explains how a plugin author can implement them.
A few notes:
In the context of this article, query refers to the database query that WordPress uses in the Loop to find the list of posts that are to be displayed on the screen ("database query" will be used in this article to refer to generic database queries). By default, the WordPress query searches for posts that belong on the currently-requested page, whether it is a single post, single static page, category archive, date archive, search results, feed, or the main list of blog posts; the query is limited to a certain maximum number of posts (set in the Options admin screens), and the posts are retrieved in reverse-date order (most recent post first). A plugin can use a custom query to override this behavior. Examples:
Before you try to change the default behavior of queries in WordPress, it is important to understand what WordPress does by default. There is an overview of the process WordPress uses to build your blog pages, and what a plugin can do to modify this behavior, in Query Overview.
Now we're ready to start actually doing some custom queries! This section of the article will use several examples to demonstrate how query modification can be implemented. We'll start with a simple example, and move on to more complex ones.
For our first example, let's consider a glossary plugin that will let the site owner put posts in a specific "glossary" category (saved by the plugin in global variable $gloss_category). When someone is viewing the glossary category, we want to see the entries alphabetically rather than by date, and we want to see all the glossary entries, rather than the number chosen by the site owner in the options.
So, we need to modify the query in two ways:
In both cases, the filter function will only make these modifications if we're viewing the glossary category (function is_category is used for that logic). So, here's what we need to do:
add_filter('posts_orderby', 'gloss_alphabetical' );
add_filter('post_limits', 'gloss_limits' );
function gloss_alphabetical( $orderby )
{
global $gloss_category;
if( is_category( $gloss_category )) {
// alphabetical order by post title
return "post_title ASC";
}
// not in glossary category, return default order by
return $orderby;
}
function gloss_limits( $limits )
{
global $gloss_category;
if( is_category( $gloss_category )) {
// remove limits
return "";
}
// not in glossary category, return default limits
return $limits;
}
To continue with the glossary plugin, we also want to exclude glossary entries from appearing on certain screens (home, non-category archives) and feeds. To do this, we will add a 'pre_get_posts' action that will detect what type of screen was requested, and depending on the screen, exclude the glossary category. We'll also use the fact that in the query specification (which is stored in $wp_query->query_vars, see above), you can put a "-" sign before a category index number to exclude that category. So, here is the code:
add_action('pre_get_posts', 'gloss_remove_glossary_cat' );
function gloss_remove_glossary_cat( $notused )
{
global $wp_query;
global $gloss_category;
// Figure out if we need to exclude glossary - exclude from
// archives (except category archives), feeds, and home page
if( is_home() || is_feed() ||
( is_archive() && !is_category() )) {
$wp_query->query_vars['cat'] = '-' . $gloss_category;
}
}
For our next example, let's consider a geographical tagging plugin that tags each post with one or more cities, states, and countries. The plugin stores them in its own database table; we'll assume the table name is in global variable $geotag_table, and that it has fields geotag_post_id, geotag_city, geotag_state, geotag_country. For this example, the idea is that if someone does a keyword search (which normally searches the post title and post content), we also want to find posts where the keyword appears in the city, state, or country fields of our plugin's table.
So, we are going to need to modify the SQL query used to find posts in several ways (but only if we're on a search screen):
With those ideas in mind, here is the code:
add_filter('posts_join', 'geotag_search_join' );
add_filter('posts_where', 'geotag_search_where' );
add_filter('posts_groupby', 'geotag_search_groupby' );
function geotag_search_join( $join )
{
global $geotag_table, $wpdb;
if( is_search() ) {
$join .= " LEFT JOIN $geotag_table ON " .
$wpdb->posts . ".ID = " . $geotag_table .
".geotag_post_id ";
}
return $join;
}
function geotag_search_where( $where )
{
if( is_search() ) {
$where = preg_replace(
"/\(\s*post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(post_title LIKE \\1) OR (geotag_city LIKE \\1) OR (geotag_state LIKE \\1) OR (geotag_country LIKE \\1)", $where );
}
return $where;
}
function geotag_search_groupby( $groupby )
{
global $wpdb;
if( !is_search() ) {
return $groupby;
}
// we need to group on post ID
$mygroupby = "{$wpdb->posts}.ID";
if( preg_match( "/$mygroupby/", $groupby )) {
// grouping we need is already there
return $groupby;
}
if( !strlen(trim($groupby))) {
// groupby was empty, use ours
return $mygroupby;
}
// wasn't empty, append ours
return $groupby . ", " . $mygroupby;
}
To continue with the geo-tagging plugin from the last example, let's assume we want the plugin to enable custom permalinks of the form www.example.com/blog?geostate=oregon to tell WordPress to find posts whose state matches "oregon" and display them.
To get this to work, the plugin must do the following:
add_filter('query_vars', 'geotag_queryvars' );
function geotag_queryvars( $qvars )
{
$qvars[] = 'geostate';
return $qvars;
}
global $wp_query;
if( isset( $wp_query->query_vars['geostate'] )) {
// modify the where/join/groupby similar to above examples
}
function geotags_list_states( $sep = ", " )
{
global $geotag_table, $wpdb;
// find list of states in DB
$qry = "SELECT geotag_state FROM $geotag_table " .
" GROUP BY geotag_state ORDER BY geotag_state";
$states = $wpdb->get_results( $qry );
// make list of links
$before = '<a href="' . get_bloginfo('home') . '?geostate=';
$mid = '">';
$after = "</a> ";
$cur_sep = "";
foreach( $states as $row ) {
$state = $row->state;
echo $cur_sep . $before . rawurlencode($state) . $mid .
$state . $after;
// after the first time, we need separator
$cur_sep = $sep;
}
}
If the blog user has non-default permalinks enabled, we can go one step further in the previous custom archives example, and enable the URL example.com/blog/geostate/oregon to also list all posts tagged with the state of Oregon. To do this, we add to WordPress's "rewrite rules", which basically tell WordPress how to interpret permalink-style URLs. Specifically, we add a rewrite rule that tells WordPress to interpret /geostate/oregon URLs the same as ?geostate=oregon. (See Query Overview for more information on the rewrite process.)
In practice, to define a new rewrite rule, there are two steps: (1) "flush" the cached rewrite rules using an init filter, to force WordPress to recalculate the rewrite rules, and (2) use the generate_rewrite_rules action to add a new rule when they are calculated. Here's the "flush" code:
add_action('init', 'geotags_flush_rewrite_rules');
function geotags_flush_rewrite_rules()
{
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
The rule generation is slightly more complex. Basically, the rewrite rules array is an associative array whose keys are regular expressions that match potential permalink URLs, and whose values are the corresponding non-permalink-style URLs they correspond to. So, to define a rewrite rule that matches URLs like /geostate/oregon (with arbitrary states), and tells WordPress it should correspond to ?geostate=oregon, we do the following:
add_action('generate_rewrite_rules', 'geotags_add_rewrite_rules');
function geotags_add_rewrite_rules( $wp_rewrite )
{
$new_rules = array(
'geostate/(.+)' => 'index.php?geostate=' .
$wp_rewrite->preg_index(1) );
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}