Skip to content

Commit

Permalink
Update post-date block to have "Time ago" format
Browse files Browse the repository at this point in the history
  • Loading branch information
amitraj2203 committed Jun 4, 2024
1 parent 661be5d commit efe5361
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
10 changes: 8 additions & 2 deletions packages/block-library/src/post-date/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import clsx from 'clsx';
*/
import { useEntityProp, store as coreStore } from '@wordpress/core-data';
import { useMemo, useState } from '@wordpress/element';
import { dateI18n, getSettings as getDateSettings } from '@wordpress/date';
import {
dateI18n,
humanTimeDiff,
getSettings as getDateSettings,
} from '@wordpress/date';
import {
AlignmentControl,
BlockControls,
Expand Down Expand Up @@ -82,7 +86,9 @@ export default function PostDateEdit( {

let postDate = date ? (
<time dateTime={ dateI18n( 'c', date ) } ref={ setPopoverAnchor }>
{ dateI18n( format || siteFormat, date ) }
{ format === 'Time Ago'
? humanTimeDiff( date, new Date() )
: dateI18n( format || siteFormat, date ) }
</time>
) : (
dateLabel
Expand Down
15 changes: 12 additions & 3 deletions packages/block-library/src/post-date/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@ function render_block_core_post_date( $attributes, $content, $block ) {
return '';
}

$post_ID = $block->context['postId'];
$formatted_date = get_the_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
$post_ID = $block->context['postId'];

if ( 'Time Ago' === $attributes['format'] ) {
$formatted_date = human_time_diff( get_post_timestamp( $post_ID, 'date' ) ) . ' ' . __( 'ago' );
} else {
$formatted_date = get_the_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
}
$unformatted_date = esc_attr( get_the_date( 'c', $post_ID ) );
$classes = array();

Expand All @@ -38,7 +43,11 @@ function render_block_core_post_date( $attributes, $content, $block ) {
*/
if ( isset( $attributes['displayType'] ) && 'modified' === $attributes['displayType'] ) {
if ( get_the_modified_date( 'Ymdhi', $post_ID ) > get_the_date( 'Ymdhi', $post_ID ) ) {
$formatted_date = get_the_modified_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
if ( 'Time Ago' === $attributes['format'] ) {
$formatted_date = human_time_diff( get_post_timestamp( $post_ID, 'modified' ) ) . ' ' . __( 'ago' );
} else {
$formatted_date = get_the_modified_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
}
$unformatted_date = esc_attr( get_the_modified_date( 'c', $post_ID ) );
$classes[] = 'wp-block-post-date__modified-date';
} else {
Expand Down

0 comments on commit efe5361

Please sign in to comment.