Proudly Presenting
Eidetic Opacity

Being The Singular Personal Blog and Virtual Soapbox of Alex Leonard

WordPress Tip: Get the date of your first post

Published on Tuesday, 27th July 2010 at 1:21pm

and featured in:
Functions

with feedback of:
Have your say!

Presented by: Alex Leonard

I’m just working on setting up a custom WordPress archive for a client at the moment (displaying posts by academic year).

In order to do things absolutely right (and in case they decide to post-publish older items), I need to be able to check when the first post was published on their WordPress installation.

I figured I’d share the code out here in case someone else finds it useful (and in case anyone can suggest improvements to the code). I’ve wrapped it up as a function so you can throw it your functions.php if it’s something you’ll re-use.

/**
 * Get First Post Date Function
 *
 * @paramĀ  $format Type of date format to return, using PHP date standard, default Y-m-d
 * @return Date of first post
 */
function ax_first_post_date($format = "Y-m-d") {
 // Setup get_posts arguments
 $ax_args = array(
 'numberposts' => -1,
 'post_status' => 'publish',
 'order' => 'ASC'
 );

 // Get all posts in order of first to last
 $ax_get_all = get_posts($ax_args);

 // Extract first post from array
 $ax_first_post = $ax_get_all[0];

 // Assign first post date to var
 $ax_first_post_date = $ax_first_post->post_date;

 // return date in required format
 $output = date($format, strtotime($ax_first_post_date));

 return $output;
}

To echo it anywhere on your site just run:

echo ax_first_post_date();

I’m hoping to be a little better at keeping track of useful WordPress functions that could be reused, so have created a sub-category of my WordPress category called “Functions”. If nothing else it will be a useful reference point for me.

Update

As soon as I hit publish I knew I should have held off until I added in a date format parameter. I’ve updated the code now so that you can tell the function what format the date should be returned in (using standard PHP date format).

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Identi.ca
  • Posterous
  • StumbleUpon
  • Tumblr
  • Twitter

Have your say!