Skip to content

Instantly share code, notes, and snippets.

@grayayer
Created May 14, 2024 00:51
Show Gist options
  • Save grayayer/d042a2dbdf44bd1f4000103bea1b053e to your computer and use it in GitHub Desktop.
Save grayayer/d042a2dbdf44bd1f4000103bea1b053e to your computer and use it in GitHub Desktop.
these are rewrite rules required to make the year filter work on the news archives
//** Custom Post Type Archive Rewrite Rules **//
function custom_news_rewrite_rules($rules) {
$new_rules = [
'company/news-room/media-coverage/([0-9]{4})/?$' => 'index.php?post_type=coverage&year=$matches[1]',
'our-news/([0-9]{4})/?$' => 'index.php?post_type=news&year=$matches[1]'
];
// This places your new rule at the top of the array to ensure it has priority.
return $new_rules + $rules;
}
add_filter('rewrite_rules_array', 'custom_news_rewrite_rules', 10, 1);
// This function checks the current URI to determine which post type should be used in the query.
// This ensures that the correct archive template is used for each post type.
function adjust_query_based_on_year($query) {
if (!is_admin() && $query->is_main_query() && get_query_var('year')) {
$year = get_query_var('year');
$query->set('date_query', [['year' => $year]]);
// Determine the correct post type based on the requested URL
// Use of $_SERVER['REQUEST_URI']: This server variable contains the current URI being accessed, which is helpful for determining the context within the WordPress query.
if (strpos($_SERVER['REQUEST_URI'], '/company/news-room/media-coverage') !== false) {
$query->set('post_type', 'coverage');
} elseif (strpos($_SERVER['REQUEST_URI'], '/our-news') !== false) {
$query->set('post_type', 'news');
}
}
}
add_action('pre_get_posts', 'adjust_query_based_on_year');
function disable_specific_canonical_redirects($redirect_url, $requested_url) {
// Prevent redirect for 'coverage' post type
if (strpos($requested_url, '/company/news-room/media-coverage') !== false && !empty(get_query_var('year'))) {
return false;
}
// Prevent redirect for 'news' post type
if (strpos($requested_url, '/our-news') !== false && !empty(get_query_var('year'))) {
return false;
}
return $redirect_url; // Otherwise, allow redirects as normal
}
add_filter('redirect_canonical', 'disable_specific_canonical_redirects', 10, 2);
remove_filter('template_redirect', 'redirect_canonical');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment