There is a function for that: human_time_diff()
. Use it like so: (U
because we want the unix timestamp)
<?php echo human_time_diff( get_the_time('U') ); ?>
If you want additional text, you can use the following
<?php printf (esc_html__('%s ago', 'yourlanguageslug'), human_time_diff(get_the_time('U'))); ?>