Archived topic
Reading time in blog and in blog title header.
3 replies · Started by Diego Carrión on January 25, 2021
Hello, I am using this code for reading time, achieved in this topic:
https://generatepress.com/forums/topic/creating-an-estimated-reading-time/
/**
* tiempo de lectura en post
*/
function tu_estimated_reading_time() {
$post = get_post();
$words = str_word_count( strip_tags( $post->post_content ) );
$minutes = floor( $words / 120 );
$seconds = floor( $words % 120 / ( 120 / 60 ) );
if ( $minutes < 2 ) {
$estimated_time = $minutes . ' minutos' . ($minutes == 1 ? '' : 's') . ', ' . $seconds . ' second' . ($seconds == 1 ? '' : 's');
} else {
$estimated_time = $seconds . ' segundos' . ($seconds == 1 ? '' : 's');
}
return $estimated_time;
}
/**
* tiempo de lectura en post
*/
add_filter( 'generate_post_author_output', function( $output ) {
$output .= '<div class="read-time">Tiempo de lectura: ' . tu_estimated_reading_time() . '</div>';
return $output;
} );
It works perfect.
Some way to be seen in the header of the blog, I have used this code.
<!-- needs this comment to work -->
<h1>
{{post_title}}
</h1>
<div class="hero-meta">
{{post_author}} | {{post_date}}
</div>
Screenshots:
https://prnt.sc/xm4l7s
Hi,
You can create a shortcode for the tu_estimated_reading_time() which you can use within the header element.
Here's the snippet:
function tu_custom_author_meta() {
ob_start();
if(function_exists ( 'tu_estimated_reading_time' )){
echo '<div class="read-time">Tiempo de lectura: ' . tu_estimated_reading_time() . '</div>';
}
return ob_get_clean();
}
add_shortcode( 'reading_time','tu_custom_author_meta' );
You can then change the markup within the Header element to this:
<!-- needs this comment to work -->
<h1>
{{post_title}}
</h1>
<div class="hero-meta">
{{post_author}} | {{post_date}} | [reading_time]
</div>
works perfectly, thank you very much.
No problem. Glad it works for you. :D