Problem: I would like to use a PHP function that counts the number of characters in custom fields, then use that number to calculate an estimated reading time. I'm using this post as a template: https://birchtree.me/blog/reading-time-wp-php/
Solution:
You can use the types_render_field function in PHP to generate the HTML markup for each field, and add that to the content string like so:
function reading_time() { $content = get_post_field( 'post_content', $post->ID ); $content .= types_render_field('field_slug', array( "id"=>$post->ID) ); $content .= types_render_field('other_field_slug', array( "id"=>$post->ID) ); // copy and paste this line as needed for additional fields $word_count = str_word_count( strip_tags( $content ) ); ... code continues ...
If the HTML applied to each field should be stripped, use the get_post_meta function instead:
function reading_time() { $content = get_post_field( 'post_content', $post->ID ); $content .= get_post_meta($post->ID, 'wpcf-field_slug', true ); $content .= get_post_meta($post->ID, 'wpcf-other_field_slug', true ); // copy and paste this line as needed for additional fields $word_count = str_word_count( strip_tags( $content ) ); ... code continues ...
Relevant Documentation:
https://toolset.com/documentation/customizing-sites-using-php/functions/
https://developer.wordpress.org/reference/functions/get_post_meta/
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 3 replies, has 2 voices.
Last updated by 6 years, 8 months ago.
Assisted by: Christian Cox.