Creating a Virtual Post in WordPress

One thing that plugin developers want to do sooner or later is create a “fake” post. (Maybe you have a statistics plugin that you want to display a public graph when someone visits example.org/traffic.) You need to create the equivalent of a Page on the fly.

Fortunately, someone has already figured out how to do just that.

The general idea is to

  1. Collect the page slug from the request
  2. See if it matches the URL we want our virtual Page to be located at
  3. Prepare the content and metadata for the fake Page
  4. Hijack the page retrieval by changing the values of some variables
  5. Display everything as usual

It seems to work pretty well, and nothing seems to break when running a plugin making use of the trick.