Dynamic Endpoints

10up engineering best practices as a great example on how to achieve that. You basically add a new rewrite tag and a new rewrite rule and then using the template_redirect action you return your custom action. Here is the code: add_action( ‘init’, function() { add_rewrite_tag( ‘%model%’, ‘([^/]+)’ ); add_rewrite_rule( ‘cars/([^/]+)/?’, ‘index.php?model=$matches[1]’, ‘top’ ); } ); … Read more

Add extra parameters after permalink?

You can add an endpoint to your URIs to handle special requests. Here is a basic example as plugin. To understand what’s going on read Christopher Davis‘s fantastic tutorial A (Mostly) Complete Guide to the WordPress Rewrite API. <?php # -*- coding: utf-8 -*- /** * Plugin Name: T5 Endpoint Example * Description: Adds a … Read more

WordPress Rest API custom endpoint optional param

You should put the named parameters of the route regex into an optional capturing group: register_rest_route( ‘api’, ‘/animals(?:/(?P<id>\d+))?’, [ ‘methods’ => WP_REST_Server::READABLE, ‘callback’ => ‘get_animals’, ‘args’ => [ ‘id’ ], ] ); The second parameter is simply a regex, thus you can use normal regex logic to make it more complex