Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Adds filters to a query
<?php
// don't use the php tags when copying this in your own theme's functions.php
function add_new_query_vars($public_query_vars) {
$public_query_vars[] = 'posts_fields';
$public_query_vars[] = 'posts_join';
$public_query_vars[] = 'posts_where';
$public_query_vars[] = 'posts_orderby';
return $public_query_vars;
}
function new_posts_fields ($fields) {
// Make sure there is a leading comma
$new_fields = get_query_var('posts_fields');
if ($new_fields) $fields .= (preg_match('/^(\s+)?,/', $new_fields)) ? $new_fields : ", $new_fields";
return $fields;
}
function new_posts_join ($join) {
$new_join = get_query_var('posts_join');
if ($new_join) $join .= ' ' . $new_join;
return $join;
}
function new_posts_where ($where) {
$new_where = get_query_var('posts_where');
if ($new_where) $where .= ' ' . $new_where;
return $where;
}
function new_posts_orderby ($orderby) {
$new_orderby = get_query_var('posts_orderby');
if ($new_orderby) $orderby = $new_orderby;
return $orderby;
}
add_filter('query_vars', 'add_new_query_vars');
add_filter('posts_fields','new_posts_fields');
add_filter('posts_join','new_posts_join');
add_filter('posts_where','new_posts_where');
add_filter('posts_orderby','new_posts_orderby');
/*
now you can query like this on your theme template files:
global $wpdb;
$args = array(
'posts_per_page' => 5,
'posts_where' => " AND $wpdb->posts.post_title LIKE 'A%'", // query for post titles that start with the letter a
);
query_posts($args);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment