Archived topic
Add reading time code
22 replies · Started by alexis on September 28, 2022
Hello I added this code in php following this post : https://generatepress.com/forums/topic/reading-time-code-to-add-to-entry-meta/
function tu_estimated_reading_time() {
$post = get_post();
$content = $post->post_content;
$wpm = 250; // How many words per minute.
$clean_content = strip_shortcodes( $content );
$clean_content = strip_tags( $clean_content );
$word_count = str_word_count( $clean_content );
$time = ceil( $word_count / $wpm );
return $time . ' min';
}
add_shortcode('reading-time', 'tu_estimated_reading_time');
Then I added a short code with this code
<?php echo '<div class="read-time">.'<span>'Temps de lecture </span> '( '[reading-time]' ) . '</div>'; ?>
But it does not work when I remove the quotes I lose the reading time (4min => 1 min) How to do please ?
I just came to the the forum to add my own issue :)
Just with this, Yoast has this automatically - would recommend exploring it!
Hi Alexis,
Where and how did you add this?
<?php echo '<div class="read-time">.'<span>'Temps de lecture </span> '( '[reading-time]' ) . '</div>'; ?>
Hi Will,
Thanks for the information :) I didn't know that!
I added this in the block gutemberg shortcode
Hi Alexis,
If it's a Shortcode Block, the shortcode should just be [reading-time]
Can you take a screenshot of how you added it?
I add this <?php echo do_shortcode("[reading-time]"); ?> but it does not work
Can you try adding just this: [reading-time] in a Shortcode Block?
Ok it's ok thanks but how to add html markup + text reading time
Alter the code you have to this:
function tu_estimated_reading_time() {
$post = get_post();
$content = $post->post_content;
$wpm = 250; // How many words per minute.
$clean_content = strip_shortcodes( $content );
$clean_content = strip_tags( $clean_content );
$word_count = str_word_count( $clean_content );
$time = ceil( $word_count / $wpm );
return '<div class="read-time"><span>Temps de lecture </span>' . $time . ' min</div>';
}
add_shortcode('reading-time', 'tu_estimated_reading_time');
Thanks perfect, you are the best 😉
You're welcome Alexis! :)
Sorry another question I want to display the reading time in my pages displayed at the bottom. Except that I need to retrieve the time according to source. Is it possible to do that? if yes how?
You can see the example at the bottom of my page: "How does a search engine work?"
For reference, can you re-share the link to the site in question?
I add in private
Will you be using a Query Loop Block or will you be adding the "For Further" section posts manually as you are now?