If you’re outputting a sitemap, there’s no reason to wait for the query for your page- which is what is producing the redirect.
Hook an earlier action and you won’t need anything to counter the trailing slash, because it won’t happen-
EDIT
Here’s a complete version with registering query vars, rules, and parse_request
action:
// add the custom query vars
// WordPress will not parse query vars in rules
// if they are not added to the list of valid query vars
function wpd_sitemap_query_var( $vars ){
$vars[] = 'svc-slug';
$vars[] = 'svc-offset';
return $vars;
}
add_filter( 'query_vars', 'wpd_sitemap_query_var' );
// add the rules
function wpd_sitemap_rewrite_rules() {
add_rewrite_rule(
'([^/]*)-svc-([0-9]+).xml',
'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]&svc-offset=$matches[2]',
'top'
);
add_rewrite_rule(
'([^/]*)-svc.xml',
'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]',
'top'
);
}
add_action('init', 'wpd_sitemap_rewrite_rules', 10, 0);
// intercept the query and test if our query var is set
// this means one of our rules matched and we should show the sitemap
function wpd_sitemap_parse_request( $query ){
if( isset( $query->query_vars['svc-slug'] ) ){
echo '<pre>';
print_r( $query->query_vars );
echo '</pre>';
// halt further execution after sitemap is output
die;
}
}
add_action( 'parse_request', 'wpd_sitemap_parse_request' );