Skip to content

Instantly share code, notes, and snippets.

@shakee93
Created May 9, 2025 15:57
Show Gist options
  • Save shakee93/1c0ce89c690b77d9f9b5e7c595d0b361 to your computer and use it in GitHub Desktop.
Save shakee93/1c0ce89c690b77d9f9b5e7c595d0b361 to your computer and use it in GitHub Desktop.
Last Updated Post time
<?php
/**
* Plugin: Latest Post Time (cache-safe)
* Version: 1.1
*/
/* ========= core helper ========= */
function rl_latest_post_relative_time() {
$posts = get_posts( array(
'posts_per_page' => 1,
'post_status' => 'publish',
'cache_results' => false,
'no_found_rows' => true,
'fields' => 'ids',
) );
if ( empty( $posts ) ) {
return '';
}
$post_id = $posts[0];
$unix = get_post_time( 'U', true, $post_id );
$diff_txt = human_time_diff( $unix, current_time( 'timestamp' ) );
return sprintf( 'Latest post about %s ago', $diff_txt );
}
/* ========= REST route ========= */
add_action( 'rest_api_init', function () {
register_rest_route(
'rl/v1',
'/latest-post-time',
array(
'methods' => 'GET',
'callback' => fn() => array( 'text' => rl_latest_post_relative_time() ),
'permission_callback' => '__return_true',
'cacheable' => false,
)
);
} );
/* ========= reusable markup ========= */
function rl_latest_post_time_markup() {
$id = 'rl-lpt-' . wp_rand();
$url = esc_url( rest_url( 'rl/v1/latest-post-time' ) );
return <<<HTML
<span id="$id" data-src="$url">Loading…</span>
<script>(function(){
const el=document.getElementById('$id');
fetch(el.dataset.src).then(r=>r.json()).then(j=>{el.textContent=j.text;});
})();</script>
HTML;
}
/* ========= shortcode ========= */
add_shortcode( 'rl_latest_post_time', 'rl_latest_post_time_markup' );
/* ========= Gutenberg block ========= */
add_action( 'init', function () {
register_block_type(
'rapidload/latest-post-time',
array(
'api_version' => 2,
'title' => 'Latest Post Time',
'category' => 'widgets',
'icon' => 'clock',
'render_callback' => 'rl_latest_post_time_markup',
'supports' => array(
'html' => false,
),
)
);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment