Wordpress-保留最初的博客发布日期,但添加第二个,最后更新的日期


Wordpress - Keep the original blog post date but add a second, last updated date

如果发布日期更新了,我会使用这个片段在发布日期旁边添加最近更新的内容:

add_filter('the_title' , 'add_update_status');
function add_update_status($html) {
    //First checks if we are in the loop and we are not displaying a page
    if ( ! in_the_loop() || is_page() )
        return $html;

//Instantiates the different date objects
$created = new DateTime( get_the_date('Y-m-d g:i:s') );
$updated = new DateTime( get_the_modified_date('Y-m-d g:i:s') );
$current = new DateTime( date('Y-m-d g:i:s') );
//Creates the date_diff objects from dates
$created_to_updated = date_diff($created , $updated);
$updated_to_today = date_diff($updated, $current);
//Checks if the post has been updated since its creation
$has_been_updated = ( $created_to_updated -> s > 0 || $created_to_updated -> i > 0 ) ? true : false;
//Checks if the last update is less than n days old. (replace n by your own value)
$has_recent_update = ( $has_been_updated && $updated_to_today -> days < 7 ) ? true : false;
//Adds HTML after the title
$recent_update = $has_recent_update ? '<span class="label label-warning">Recently updated</span>' : '';

    //Returns the modified title
    return $html.'&nbsp;'.$recent_update;
}

我希望我的帖子显示以下内容:发布于2012年10月8日上午9:07,最后更新于2013年11月6日上午11:03

我们如何才能做到这一点?

在创建和更新新帖子时使用WordPress的这些动作挂钩。在创建新的帖子时,使用插入钩子,在更新帖子时使用WordPress的保存钩子。

创建一个帖子元,存储创建帖子和更新帖子的时间,如下所示。

//添加或更新时

add_action( 'save_post', 'my_save_post');
function my_save_post($post_id){
    if(empty(get_post_meta($post_id, 'created_on', true))) {
        update_post_meta($post_id, 'created_on', date('Y-m-d h:i:s'));    
    }
    update_post_meta($post_id, 'updated_on', date('Y-m-d h:i:s'));
}

现在,当你需要将创建和更新的时间显示在你的主题中时,请使用如下所示的功能:

显示创建的时间

get_post_meta($post_id, 'created_on', true);

显示更新时间

get_post_meta($post_id, 'updated_on', true);

您可以将其添加到您的帖子模板中:

Published on <?php echo get_the_date('F j, Y'); ?> at <?php the_time('g:i a'); ?>, Last modified on <?php the_modified_date('F j, Y'); ?> at <?php the_modified_date('g:i a'); ?>