All Posts

Reading Time Dynamic Content

Published: November 29, 2023
Share:
Image

Did you know that you can relatively easily tap into the Cornerstone builder’s native dynamic content feature via the Dynamic Content API and create your own custom fields of dynamic content? It’s true. In this tutorial we’re going to look at how to create a custom read time value that is calculated based on the page’s text length and we’re going to do it all without needing to add feature specific plugins.

The best part? I’ve included the code below.

To take this further and create your own custom dynamic content, don’t be intimidated, the video also covers how to leverage ChatGPT to generate the proper code for you with 1-2 simple prompts.

Here is the code used in the tutorial to create the custom read time value. Simply paste this into your functions.php and you’ll be in business.


// Cornerstone Custom Dynamic Content - Reading Time

class ReadTimeDynamicContent {

  const GROUP = "custom_dynamic_content";

  static public function setup() {
    add_filter('cs_dynamic_content_' . self::GROUP, [self::class, 'calculateReadTime'], 0, 4);
    add_action('cs_dynamic_content_setup', [self::class, 'register']);
  }

  static public function register() {
    cornerstone_dynamic_content_register_group([
      'name'  => self::GROUP,
      'label' => "Custom Dynamic Content",
    ]);

    cornerstone_dynamic_content_register_field([
      'name'  => 'reading_time',
      'group' => self::GROUP,
      'label' => 'Reading Time',
      'controls' => [
        [
          'key'     => 'minutes',
          'type'    => 'number',
          'label'   => 'Minutes',
        ],
      ],
    ]);
  }

  static public function calculateReadTime($result, $field, $args = []) {
    switch ($field) {
      case 'reading_time':
        $content = get_post_field('post_content', get_the_ID());
        $word_count = str_word_count(strip_tags($content));
        // Average reading speed is 200 words per minute
        $minutes = ceil($word_count / 200);
        $result = ['minutes' => $minutes];
        break;
      default:
        break;
    }
    return $result;
  }

}

add_action("init", [ReadTimeDynamicContent::class, "setup"]);