I'm trying to catch the params sent by the rewrite rules and then display a selected post.
But for now, even if I can retrieve those param, the page redirect to the archive of my custom post type. Where I need to display the post that match a custom query build from the query string given by the rewrite rule.
add_action('init', function () {
$terms_slug = getCustomTermsSlug();
// @note Catch /{foo}
add_rewrite_rule('^(' . implode('|', $terms_slug) . ')/?', 'index.php?post_type=custom&foo=$matches[1]', 'top');
});
add_action('init', function () {
add_rewrite_tag('%foo%', '([^&]+)');
}, 10, 0);
add_action('pre_get_posts', function ($query) {
if (is_admin() || !$query->is_main_query()) {
return;
}
if (get_query_var('foo')) {
$tax_query = [[
'taxonomy' => 'custom',
'field' => 'slug',
// @note "foo" is a custom taxonomy term
'terms' => get_query_var('foo'),
]];
$query->set('tax_query', $tax_query);
}
return $query;
});
First, I don't understand why it redirect to the archive page?
Second, maybe the "pre_get_posts" is not the right place to make the customized query but where I can do it then?
Third, how to display the selected post in response of the clean URL given?
Thank's for your help! ;-)
@EDIT I've tried using actions like "template_redirect" or "parse_request" but it feel really *hacky. Is anyone know how to force the redirect (eg. rewrite matching) to the first post of the custom query?
$args
but don't set it anywhere.