I’m going to demonstrate how to have a URL with content in WordPress that’s neither a post, page, or listing. Its contents can be anything you’d like!
To do this we need to take the following steps:
- Add a custom query variable
- Add a rewrite rule that uses the new query variable
- On the
template_redirecthook, check if that variable is set in the current query - If it is, render our own content then exit early
A Helper Class
I’ve encompassed all these steps into a base class, which you can inherit from:
View the code on Gist.
To use it, create a new class extending it, and implement the render_page method. Then pass in the needed options on creation for the desired URL and the page identifier.
For example, this is how you would add a page at example.com/helloworld that prints out the classic phrase:
View the code on Gist.
Finally place this in a plugin, activate, and flush your permalinks to see the full effect. You could go further by adding in calls to get_template_part() to make use of your theme.
If you’d like to integrate into a theme from a plugin, try calling the page.php template via get_template_part, and add a filter to the_content and the_title to display your plugins content inside the sites theme.
Leave a Reply