Pretty recently, I had to add a “Site last updated” feature to the footer of a WordPress site. Now there’s a couple of plug-ins that will do this automatically for you but if all you really need is the date of the last update, all of these plug-ins are a little over the top. Believe it or not, everything you need is built right into WP in the get_lastpostmodified() function. And with a little more PHP we can take this value and format it any way we like.
Let’s have a look…
The WP function get_lastpostmodified() retrieves the last time a post was modified. But that’s it, it just retrieves the value. To get it to show up, just echo the function.
1 | <?php echo get_lastpostdate(); ?> |
You now should have something like this:
2009-11-10 11:38:47
That’s the raw date format from the database, but with a little more PHP we can take this value and make it pretty. As you probably can guess, we’re going to use the PHP Date function.
Here’s our code:
1 | <?php echo date("F j, Y", strtotime(get_lastpostmodified())); ?> |
Ok so what’s all that…
We call the PHP Date function with date — pretty obvious, I know. Next we tell it what format we want — I’m using F j, Y but there’s a lot more ways you can output this — check the function reference to find the format you want. Our example will give us a format like this: November 13, 2009. The important parts of this are the alphabetic characters; commas, dashes, spaces are optional.
Next we use the WordPress function get_lastpostmodified as a value for strtotime. The strtotime takes then takes our value, expects be a US English timestamp and then tries to parse it to a UNIX timestamp. The UNIX timestamp then can be formatted with our F j, Y and the date function tells it how to be handled.
No clunky plug-ins to manage, just a single line that does it’s thing. Pretty simple right?
Thank you very much, it helped me!
Thanks a lot! It saved my life in a second, just did copy paste your one line of code and this is exactly what I needed.
Keep up the good work.