Content Without Posts

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.

4 thoughts on “Content Without Posts

    • 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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.