Last updated on September 13, 2023

Custom Rewrite Endpoint

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Add a custom rewrite endpoint.

Custom rewrite endpoints in WordPress allow you to add a new URL structure to your site that provides additional information beyond what’s included in the query string. This can be useful for creating custom views or templates for your content. Here’s an example code snippet to add a custom rewrite endpoint in WordPress:

function wpsnippets_custom_rewrite_endpoint() {
    add_rewrite_endpoint( 'my-endpoint', EP_PERMALINK );
}

add_action( 'init', 'wpsnippets_custom_rewrite_endpoint' );

In this code snippet, we define a function wpsnippets_custom_rewrite_endpoint() that sets a custom rewrite endpoint using the add_rewrite_endpoint function. The first parameter sets the name of the endpoint, which will be appended to the URL structure after a /. The second parameter sets the endpoint’s position in the URL structure. In this example, we set it to EP_PERMALINK to make it part of the permalink structure.

Finally, we add the wpsnippets_custom_rewrite_endpoint function to the init action using the add_action function to ensure that the rewrite endpoint is added at the appropriate time during WordPress initialization.

With this code in place, you can now visit URLs on your site with the custom endpoint, such as https://example.com/my-page/my-endpoint, and WordPress will recognize the endpoint and include it in the query variables for the page. You can then use the get_query_var function to retrieve the value of the custom endpoint and use it to modify the display of the page.

Note that adding a custom rewrite endpoint requires flushing the rewrite rules in WordPress, which can be done by visiting the “Settings > Permalinks” page in the WordPress admin area.

Last updated on September 13, 2023. Originally posted on May 12, 2023.

Leave a Reply