Using WordPress ‘add_rewrite_endpoint()’ PHP function

The add_rewrite_endpoint() WordPress PHP function adds an endpoint to the WordPress rewrite system, like /trackback/. This function allows you to add rewrite rules for each specified matching location provided by a bitmask. This function also creates a new query variable named after the endpoint.

Usage

Below is a generic example of how to use the function:

add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES );

In this example, a new rewrite rule ending with “json(/(.*))?/?$” is added for every permalink or page structure. This is rewritten to “json=$match” where $match is the part of the URL matched by the endpoint regex.

Parameters

  • $name (string – required): Name of the endpoint.
  • $places (int – required): Endpoint mask describing the places the endpoint should be added. Accepts a mask of various EP_* constants.
  • $query_var (string|bool – optional): Name of the corresponding query variable. Pass false to skip registering a query_var for this endpoint. Defaults to the value of $name.

More information

See WordPress Developer Resources: add_rewrite_endpoint()

This function is part of the Rewrite Endpoint API. Make sure to flush the rewrite rules by using the flush_rewrite_rules() function when your plugin gets activated and deactivated.

Examples

add_rewrite_endpoint( 'json', EP_PERMALINK );

This code adds a ‘json’ endpoint to all permalinks in your WordPress site.

Add a ‘pdf’ endpoint to attachment URLs

add_rewrite_endpoint( 'pdf', EP_ATTACHMENT );

This code adds a ‘pdf’ endpoint to all attachment URLs.

Add a ‘print’ endpoint to page URLs

add_rewrite_endpoint( 'print', EP_PAGES );

This code adds a ‘print’ endpoint to all page URLs.

Add a ‘feed’ endpoint to category URLs

add_rewrite_endpoint( 'feed', EP_CATEGORIES );

This code adds a ‘feed’ endpoint to all category URLs.

Add an ‘api’ endpoint to all locations

add_rewrite_endpoint( 'api', EP_ALL );

This code adds an ‘api’ endpoint to all URLs in your WordPress site.