Varnish ESI & Wordpress - simulate loading a post

533 views Asked by At

Update: I've answered this myself. See below.

I guess I'm asking for the equivalent of a set_the_id() function, if one existed.

I'm using Wordpress with Varnish for performance, and I want to use an ESI (Edge Side Include) for the sidebar, so things like recent/popular posts can be refreshed more frequently than the post content itself.

One way of doing this is creating an endpoint in your plugins directory etc. for Varnish to access from an ESI comment, with some code like this:

<?php
/* ESI handler for Varnish - Sidebar (all tabs except search) */

$cwd = getcwd();
$path = substr($cwd, 0, strpos($cwd, 'wp-content/'));
require $path . 'wp-blog-header.php';


    echo '<!-- ESI sidebar created '.date(DATE_RFC2822).' -->',"\n";
    if ( ! dynamic_sidebar( 'primary-widget-area' ) )
    {
        echo '<!-- Unable to load primary-widget-area (sidebar) -->';
    }
?>

All fine so far; this is enough to load Wordpress and it to find all the relevant plugins. However they produce errors at various points (specifically wp-includes/post-template.php line 29) because they need to use things like get_the_id(), in_category() and properties of the post object to highlight certain posts and so on and no post has been loaded yet.

How can I tell Wordpress to load a specific post ID in the code above, as if I'd gone to a URL like http://example.com?p=1, but without outputting a full page? I just want the environment to be setup as if post was active, then I can pass the current post ID as a parameter in my ESI call.

I thought query_posts() might help and I tried adding:

query_posts( 'p=5' );

but it doesn't do anything.

I also wondered about WP_Post::get_instance() (it only seems to take an object though, not a post ID).

Is there anything else I can use?

1

There are 1 answers

0
William Turrell On
$query = new WP_Query( 'p=1' );

if ( $query->have_posts() ) {
    $query->the_post();   // this loads it
}

See http://codex.wordpress.org/Class_Reference/WP_Query for all the other parameters.