Custom Taxonomy Template Post List with Sort Order

The most efficient way is probably to hook into the pre_get_posts action and add your time comparison there. This way you don’t have to worry about the rest or the query options as they will still work. It should look like this (untested), and be placed in a plugin or theme functions file (not in the page template file, the query will already have been executed):

add_action('pre_get_posts', 'add_event_date_criteria');
function add_event_date_criteria(&$query)
{
    // We only want to filter on "public" pages
    // You can add other selections, like here:
    //  - Only on a term page for our custom taxonomy
    if (!is_admin() &&
        is_tax('event_types')) {
        global $custom_metabox_event_dates;
        $query->set('meta_key', $custom_metabox_event_dates->get_the_name('combined_datetime'));
        $query->set('meta_compare', '>=');
        $query->set('meta_value', time());
        $query->set('orderby', 'meta_value');
        $query->set('order', 'asc');
    }
}

You define the scope of this extra filter with the contents of the if() test. Currently we don’t do it on admin pages (you wouldn’t be able to access old content), and only do it on specific taxonomy pages. You should find out for yourself how wide or how narrow you want this.

If you can’t solve it this way, you can do the main query again without losing the “page specific query” by adding the different query vars to the main $wp_query objects, and calling $wp_query->get_posts() again. Since we did not call $wp_query->parse_query(), the page-specific query args will not be cleared. It would look like this:

global $custom_metabox_event_dates;
$wp_query->set('meta_key', $custom_metabox_event_dates->get_the_name('combined_datetime'));
$wp_query->set('meta_compare', '>=');
$wp_query->set('meta_value', time());
$wp_query->set('orderby', 'meta_value');
$wp_query->set('order', 'asc');
$wp_query->get_posts();

You can place this in your template files (not functions.php, but taxonomy-event_types.php or other “real” template files). Remember that you “throw away” one database call this way, so it is not the most optimal solution.

Leave a Comment