Sending your WordPress posts back / forward in time

Fancy sending your WordPress site back (or forward) in time for a day? Thanks to the multitude of filters it only takes a few lines of code. In this example I’m just going to filter the_time(), but in a future post I will also show you how to put together a more comprehensive function that uses multiple filters (and has a more practical use).

The filter for the_time() passes two values in – the value it was going to display, and the formatting string used to create it.

Hooking in to the filter

This is fairly standard – pass the name of the filter we are using to the function add_filter(), along with the name of our custom function that is going to modify the value:

add_filter( 'the_time', 'cc_time_machine' );

However, since we need both of the arguments that the filter passes, we have to add in the optional values for ‘priority’ and ‘accepted arguments’. The default priority is ten, and as mentioned there are two arguments – so that gives us:

add_filter( 'the_time', 'cc_time_machine', 10, 2 );

Travelling in time:

Now we can receive the data in our function and modify the value. None of the arguments relate to the ID of the post being dealt with, but we can use the global `$post` variable to retrieve it. Then we use the get_the_time() function to retrieve the date/time of the post in timestamp format – this makes it easy to manipulate. Let’s send everything 30 days into the past:

$timestamp = get_post_time( 'U', true, $post );
$adjusted = $timestamp + ( -30 * DAY_IN_SECONDS );

Finally, we need to return the new value. Utilising the second argument ensures we format the date in the same way as it was originally requested:

return date( $format, $adjusted );

The complete function:

N.B. this version reads the time travel value ($offset) from the database so it can be controlled through wp-admin.

Category:

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *