Post preview mechanism architecture

Even if you hit just one button for “Preview” it may ends in 2 different “routes”.

The one is something like

http://example.com/postname/?preview=true

The second is something like:

http://example.com/postname/?preview_id=152&preview_nonce=xxx&preview=true

so the first contains preview query argument, the second contains

  • preview_id
  • preview_nonce
  • preview

query arguments.

preview query argument tells WordPress to allow visualization of non-published posts to users with proper capabilitites.

If you have a post saved as “draft”, and you are logged in, you can view it in front-end just like it was published, simply adding ?preview=true to the post url.

The second kind of url are attached to preview button via javascript when a post autosave runs.

An autosave stores the post as it is (so including any change) in posts table, but replacing actual post type with type “revision”.

Find more information here.

Autosave runs at regular intervals on backend, but also runs when you click the “Preview” button, in this way in the preview screen you always see last changes.

This is what happen:

  1. You click “Preview” button
  2. WordPress stores current post in posts table as revision
  3. A browser page with post url and preview_id, preview_nonce and preview query argument is opened
  4. WordPress pulls the post object from posts table
  5. Because of preview query argument is present, WordPress
    1. Verifies current user is logged and has proper capabilities
    2. Verifies nonce
    3. If previous checks pass, WordPress pulls last post revision from database, ensuring that revision post name and post author matches post name and post author of post object pulled at point 4
    4. If a valid revision is found, the post object pulled at point 4 is replaced with revision post object

Besides of that, a preview is handled the same way of normal front-end request for a sigular post, but once the post object used to display the page is taken from revision database row, you see the last, even not saved, post changes.

Leave a Comment