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' );
} );

add_action( 'template_redirect', function() {
  global $wp_query;

  $model = $wp_query->get( 'model' );

  if ( ! empty( $model ) ) {
    // Return stuff here
  }
} );

Don’t forget to flush permalinks before trying your new endpoint!
Using wp-cli:

wp rewrite flush

Or using the admin UI: http://example.local/wp-admin/options-permalink.php and click save.

Leave a Comment

tech