Archived topic
Read time as post meta data
5 replies · Started by Alfredo on March 23, 2023
I'm using GPT's help to try to add a function to store reading time as post meta data and then pull it using dynamic content from Generate Blocks. I want to display it in the post content template (block) and blog content template (block) I created.
But when I call the metakey reading_time in dynamic content of GB nothing is displayed. In the preview of the block - content template for blog archives I see it displays 0 (which is not right either).
This is the code:
function read_time() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
$read_time = ceil( $word_count / 240 );
return $read_time;
}
function add_reading_time_meta_key() {
register_post_meta( 'post', 'reading_time', array(
'type' => 'number',
'description' => 'Estimated reading time in minutes',
'single' => true,
'show_in_rest' => true,
) );
}
add_action( 'init', 'add_reading_time_meta_key' );
function update_reading_time_meta_key( $post_id ) {
if ( ! isset( $_POST['post_type'] ) || 'page' === $_POST['post_type'] ) {
return;
}
$read_time = read_time();
update_post_meta( $post_id, 'reading_time', $read_time );
}
add_action( 'save_post', 'update_reading_time_meta_key' );
Could you help me with this?
Hi there,
see the reply here:
https://generatepress.com/forums/topic/reading-time-in-query-loop-latest-posts/#post-2465893
Great! It works
Is it supposed to be formatted with GB? I'm not able to change the format. If I try to change something in the placeholder headline it applies the new formatting in the editor to all items inside the flex container (although I'm only formatting one item) but then the changes are not displayed.
Image for reference:
https://ibb.co/LJRNKkf
Hi Alfredo,
Yes, setting it through GB Block Settings should work. Set the change to the Headline Block with the class reading-time only. If you are setting it as such already and it isn't working as expected, let us know.
Yes, that is exactly what I'm doing. When trying to edit the Headline Block with the class reading-time every item in the container that you can see in the screenshot is changed.
Can you try these:
a) Choose Inline Embedding for the CSS Print Method in Settings > GenerateBlocks.
If a) doesn't work:
b) Regenerate your CSS files in Settings > GenerateBlocks.