You can’t add arbitrary query variables to the rewrite rules, there’s a whitelist of allowed variables.
To add a query variable, use query_vars
filter, e.g. this filter adds my-api
as a valid query variable:
function wpd_query_vars( $query_vars ){
$query_vars[] = 'my-api';
return $query_vars;
}
add_filter( 'query_vars', 'wpd_query_vars' );
But that just gets you the query variable, you still need to do something with it. Rewrite rules map pretty URLs on to query variables, nothing more. That’s why a rewrite rule that doens’t map to index.php
won’t work.
Instead, you then need to write a hook that looks for when your new query variable is defined, and if so, do what you want that page to do.
Most people will use the template_redirect
hook and load a custom template, e.g.
add_action( 'template_redirect', 'custom_page_template_redirect' );
function custom_page_template_redirect() {
global $wp_query;
$custom_page = $wp_query->query_vars['my-api'];
if ( $custom_page == 'key' ) {
// we've found our page, call render_page and exit
echo "hooray! it works!";
exit;
}
}
Where instead of outputting Hooray, or loading a template, you’d call wp_safe_redirect()
to redirect the user to a destination of your choice ( or wp_redirect
if it’s offsite )