add_rewrite_endpoint()
only supports static endpoint names like trackback
and recipes
, so if you need a dynamic endpoint name/slug, then you would want to use add_rewrite_rule()
instead.
And just so that you know, even if add_rewrite_endpoint()
did support dynamic names/slugs, your code would not work because your function runs too early (via the init
hook) and thus get_queried_object()
would return a null, which means that $term
is not actually an object (even if you were on a term archive page).
So for the food/onion/onion-recipes
structure or endpoint, where onion
is the term slug, you could use add_rewrite_rule()
like so:
add_action( 'init', function () {
// Adds a rewrite rule for /food/<term slug>/<term slug>-recipes where "food"
// here is a custom taxonomy.
add_rewrite_rule(
'food/(.+?)/([^/]+)-recipes/?$',
'index.php?food=$matches[1]',
'top'
);
} );
Things to note:
-
(.+?)
is a term slug or path which is read from the current URL path, and the slug could beonion
or a “directory”/path likeonion/child
if your taxonomy is hierarchical. -
([^/]+)
is also a term slug, but without a/
(slash). (I purposely put it in a group in case you’d need to access$matches[2]
) -
In the above regular expression (RegEx) pattern (which is the 1st parameter for
add_rewrite_rule()
), I used 2 capturing groups or subpatterns, and each group/subpattern match from the URL will be stored in an array named$matches
.So if the current URL is
https://example.com/food/onion/child/child-recipes
, then$matches[1]
isonion/child
, whereas$matches[2]
ischild
. I.e.food/(onion/child)/(child)-recipes
— note the parentheses.
You can test and play with the above RegEx here on regex101.com.
Also, remember to flush the rewrite rules! Simply visit the Permalink Settings admin page.
Update
If you want to create a query var for your endpoint, just like what add_rewrite_endpoint()
does by default, and so that you can use get_query_var()
to retrieve the term slug from the endpoint name, you can use the query_vars
hook to register your query var.
Here’s an example where the query var (name) is food_recipe
(make sure the name is not already in use, e.g. by an existing post type or taxonomy):
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'food_recipe';
return $vars;
} );
After that,
-
Change the rewrite rule’s query (the 2nd parameter for
add_rewrite_rule()
) fromindex.php?food=$matches[1]
toindex.php?food=$matches[1]&food_recipe=$matches[2]
-
Then flush the rewrite rules, again. 🙂
And as for using &food-info=recipes
in the above query, where food-info
is a custom taxonomy name/slug, yes, you can. Any query args that WP_Query
accepts, and even custom ones, can be used there, but whether the query would return any posts would of course depend on whether there are posts that matched the query. 🙂