Skip to content

Instantly share code, notes, and snippets.

@benmay
Created November 4, 2012 01:39
Show Gist options
  • Save benmay/4009754 to your computer and use it in GitHub Desktop.
Save benmay/4009754 to your computer and use it in GitHub Desktop.
Filter Custom Post Type, Taxonomy by date archives
/*
Problem was, a custom post type, with custom taxonomy, and then wanted to have a dropdown of archives by month/year. wp_get_archives() wouldn't work clearly.
Rewrite rule required to be added:
$new_rule = 'media-centre/format/media-releases/archives/(.+)/(.+)/?$' => 'index.php?post_type=mc&mc-format=media-releases&year=' . $wp_rewrite->preg_index(1) .'&monthnum=' . $wp_rewrite->preg_index(2);
*/
/*
* Dropdown of media releases grouped by date.
*/
function media_releases_dropdown()
{
$args = array(
'post_type' => 'mc',
'mc-format' => 'media-releases',
'posts_per_page' => -1
);
add_filter( 'posts_clauses', array('Dr', 'filter_query' ) );
$archives = new WP_Query( $args );
remove_filter( 'posts_clauses', array('Dr', 'filter_query' ) );
$months = array();
// Loop through the posts, and group into a year-month array for the dropdown.
foreach ( $archives->posts as $record ){
$key = date( 'Y/m', strtotime( $record->post_date ) );
$val = date( 'F Y', strtotime( $record->post_date ) );
$months[ $key ] = $val;
}
echo '<h3>Filter by Month</h3>';
echo '<form id="month-filter"><select name="theurl" id="theurl" onchange="window.location.href=this.form.theurl.options[this.form.theurl.selectedIndex].value">';
echo '<option value="/media-centre/format/media-releases/">-- All --</option>';
foreach( $months as $k=>$v){
// Set if current
list($y,$m) = explode('/',$k);
$selected = ( $m == get_query_var('monthnum') && $y == get_query_var('year') ? 'selected="selected"' : '' );
// Set URL to redirect to
$k = get_bloginfo('url') . '/media-centre/format/media-releases/archives/' . $k . '/';
// Echo the option
echo "<option value=\"$k\" $selected>$v</option>";
}
echo '</select></form>';
}
function filter_query( $var )
{
$var['groupby'] = 'YEAR( wp_posts.post_date ), MONTH( wp_posts.post_date )';
return $var;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment