Skip to content

Instantly share code, notes, and snippets.

@psaia
Created March 7, 2012 20:06
Show Gist options
  • Save psaia/1995670 to your computer and use it in GitHub Desktop.
Save psaia/1995670 to your computer and use it in GitHub Desktop.
wordpress where clause overwrite to query on custom field
<?php
// If on events page get only upcoming events.
if (segments(2) === 'events' AND ! is_single())
{
// Our query overwrite. Fancy, hacky, wonderful.
function filter_where($where = '')
{
global $wpdb;
$now = strtotime('now'); // Get current timestamp.
// Overwrite entire where clause to get the upcoming events.
$where = "AND wp_posts.post_type = 'events' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')".
" AND wp_postmeta.meta_key = 'date_of_event' AND UNIX_TIMESTAMP(wp_postmeta.meta_value) >= $now";
return $where;
}
// Add the where filter.
add_filter('posts_where', 'filter_where');
// Preform query.
query_posts(array(
'post_type' => 'events',
'order' => 'ASC',
'paged' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
// Need to add this so query_posts joins the postmeta table in the query.
// Above I overwrite the where bit and use meta. Via filter_where()
'meta_query' => array(array('key' => '','value' => '','compare' => '','type' => ''))
));
// Remove the filter.
remove_filter('posts_where', 'filter_where');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment