Created
February 9, 2015 22:48
-
-
Save kcpt-steven-kohlmeyer/f5c5115de8a44598f97d to your computer and use it in GitHub Desktop.
Wordpress script to create custom pretty urls, and set query variables for filtering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function customQueryVar($vars) { | |
$vars[] = "year_filter"; | |
return $vars; | |
} | |
// hook add_query_vars function into query_vars | |
add_filter('query_vars', 'customQueryVar'); | |
function custom_rewrite_rule() { | |
add_rewrite_rule('^year-posted/([^/]*)?','index.php?post_type=posts&year_filter=$matches[1]','top'); | |
} | |
add_action('init', 'custom_rewrite_rule', 10, 0); | |
function alterQuery($query) { | |
if ( ! is_admin() and $query->is_main_query() && is_post_type_archive('post') ) { | |
$year = date('Y', current_time( 'timestamp' ) ); | |
if( isset( $wp_query->query_vars['year_filter'] ) ) { | |
$yearSet = $wp_query->query_vars['year_filter']; | |
} | |
if( isset( $yrNominated ) and ! empty( $yrNominated ) ) { | |
$yearSet = (int) $yearSet; | |
// Ensure the year requested is real | |
if( $yearSet > 1000 and $yearSet < 2100 ) { | |
$year = $yearSet; | |
} | |
} | |
$query->set( 'meta_query', array( | |
array( | |
'key' => 'year', | |
'value' => $year, | |
'compare' => '=' | |
) | |
) ); | |
} | |
} | |
add_action('pre_get_posts','alterQuery'); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$yearRequested = get_query_var( 'year_filter', false ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment