Pergunta

In response to the question asked here I find myself and this other user needing a solution to set a last modified header that contains the date and time of the most reicent post. Since we both in many themes have the home page set to a static page and then coding our dynamic content into the static files we are missing that important header to make sure cached homepages update when there are new posts.

So, how can we set a last modified HTTP header on a page that it set to the most recent Post?

Foi útil?

Solução

Last-Modified header for visitors on the front-page

It's useful to see how the Last-Modified header is added to the feeds, in the wp::send_header() method.

If we want to be able to use is_front_page(), then the filters wp_headers or send_header are probably applied to early.

We could instead use the template_redirect hook to target the front-page, before the headers are sent and after is_front_page() is ready.

Here's an example:

/**
 * Set the Last-Modified header for visitors on the front-page 
 * based on when a post was last modified.
 */

add_action( 'template_redirect', function() use ( &$wp )
{
    // Only visitors (not logged in)
    if( is_user_logged_in() )
        return;

    // Target front-page
    if( ! is_front_page() )
        return;

    // Don't add it if there's e.g. 404 error (similar as the error check for feeds)
    if( ! empty( $wp->query_vars['error'] ) )
        return;

    // Don't override the last-modified header if it's already set
    $headers = headers_list();
    if( ! empty( $headers['last-modified'] ) )  
        return;

    // Get last modified post
    $last_modified = mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), false );

    // Add last modified header
    if( $last_modified && ! headers_sent() )
        header( "Last-Modified: " . $last_modified . ' GMT' );

}, 1 );

Here we used the core PHP functions header(), headers_list() and headers_sent() and the WordPress core function get_lastpostmodified()

The Etag header could be added here too as the md5 of the last modified date.

We can then test it from the command line with e.g.:

# curl --head https://example.tld

or just use the shorthand parameter -I to only fetch the HTTP headers.

Outras dicas

Untested, but it should work:

$query = "SELECT MAX(post_modified) AS modified FROM {$wpdb->prefix}posts";
$results = $wpdb->get_results($query);

if (isset($results[0]->modified) {
    header("Last-Modified: ".$results[0]->modified);
}
add_action('template_redirect', 'theme_add_last_modified_header');

function theme_add_last_modified_header($headers) {
    global $post;
    if(isset($post) && isset($post->post_modified)){
        $post_mod_date=date("D, d M Y H:i:s",strtotime($post->post_modified));
        header('Last-Modified: '.$post_mod_date.' GMT');
     }
}

This worked for me on posts and pages :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange
scroll top