Search code examples
wordpressdatecustom-post-type

Get last post date for custom post type - Wordpress


This is probably a simple one but I can't seem to find an answer anywhere.

I have 2 custom post types. I display them in sections on my home page.

In each section I'd like to have "Last Updated [DATE]" text near the title for each section.

I've found <?php get_lastpostdate( $timezone ) ?> but is there a way of specifying which post type you'd like to query?

[UPDATE]

Here's the final code I used based on Howdy_McGee's answer below. I wanted the date to read as "16th May" for example. `Thanks, that's the route I started to go down as well. I guess I was hoping to not do another WP_Query, but it works. This is the final code I used:

<p class="right last-update"><?php 
    $latest = new WP_Query(array('post_type' => 'car', 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'modified', 'order' => 'ASC'));
    if($latest->have_posts()){
        $modified_date = $latest->posts[0]->post_modified;
    }
    //Get the last post update and display the date as "10th March"
    $lastpost = strtotime($modified_date);
    $lastmonth = date('F', $lastpost);
    $lastday = date('jS', $lastpost);
    echo 'Last Updated '.$lastday.' '.$lastmonth;
    ?>
</p>

Solution

  • You can use the_post_modified() function if you're in The Loop. The modified date will change any time the post is changed in any way / updated in any way.

    Update

    Ok, lets run a small query, what this does is pulls the latest post, modified or new. Since it's just 1 post we can just check if it has posts, and get the first posts modified date.

    <?php 
        $latest = new WP_Query(
            array(
                'post_type' => 'car',
                'post_status' => 'publish',
                'posts_per_page' => 1,
                'orderby' => 'modified',
                'order' => 'DESC'
            )
        );
    
        if($latest->have_posts()){
            $modified_date = $latest->posts[0]->post_modified;
        }
    ?>
    

    For a full list of Date Format Options, View Codex. If you're using it outside The Loop, you can use get_the_modified_date() function. Hope it helps!