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_redirect
hook, 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.
@Tarendai or you can just use parse_request, no?
@NaomiCBush Yes! That slipped my mind! Only one filter to swap out mind
All fine and dandy, but how about a couple of example use cases?
I needed to build a dashboard plugin, and rather than add a page template and template tags etc, I added a /dashboard URL.
Another example might be to ask or view poll and survey results or to view data from custom tables or remote tables. Most use cases I imagine would involve plugins and perhaps the option for theme templates without the use of pages and posts etc, e.g. The shopping cart in an e commerce plugin