How to get the last updated date of a post from a WP RSS feed?

Atom vs RSS2

Let’s look at the wp-includes/feed-atom.php and wp-includes/feed-rss2.php files.

The updated element of the Atom feed entry is:

<updated><?php 
    echo mysql2date(
        'Y-m-d\TH:i:s\Z', 
        get_lastpostmodified('GMT'), 
        false 
    ); 
?></updated>

The pubDate element of the RSS2 feed item is:

<pubDate><?php 
    echo mysql2date(
        'D, d M Y H:i:s +0000', 
        get_post_time('Y-m-d H:i:s', true), 
        false
    ); 
?></pubDate>

The lastBuildDate element of the RSS2 channel is:

<lastBuildDate><?php 
    echo mysql2date(
        'D, d M Y H:i:s +0000', 
        get_lastpostmodified('GMT'), 
        false
    ); 
?></lastBuildDate>

Namespace

The RSS2 feed already contains the Atom namespace:

xmlns:atom="http://www.w3.org/2005/Atom"

so I think we can use the <atom:updated> element for our custom updated element. You might want to check it out further, if that fulfills the standard or if there are other possible namespaces suitable for this.

For the latter case we can use the rss2_ns action to add the relevant namespace.

Inject a custom element

We can use the rss2_item action to inject custom item elements, like:

add_action( 'rss2_item', function()
{   
    printf( 
        '<atom:updated>%s</atom:updated>',
         get_post_modified_time( 'D, d M Y H:i:s +0000', true )
    );

} );

Hopefully you can adjust it to your needs.

Leave a Comment

tech