| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPDeveloper\BetterDocs\Shortcodes; |
| 4 |
|
| 5 |
use WPDeveloper\BetterDocs\Core\Shortcode; |
| 6 |
|
| 7 |
class ReadingTime extends Shortcode { |
| 8 |
public function get_name() { |
| 9 |
return 'betterdocs_reading_time'; |
| 10 |
} |
| 11 |
|
| 12 |
public function get_style_depends() { |
| 13 |
return [ 'reading-time' ]; |
| 14 |
} |
| 15 |
|
| 16 |
public function default_attributes() { |
| 17 |
return [ |
| 18 |
'reading_title' => '', |
| 19 |
'reading_text' => __( 'min read', 'betterdocs' ), |
| 20 |
'singular_reading_text' => __( 'min read', 'betterdocs' ), |
| 21 |
'content' => __( 'Reading Time', 'betterdocs' ), |
| 22 |
'the_content' => get_the_content() |
| 23 |
]; |
| 24 |
} |
| 25 |
|
| 26 |
public function render( $atts, $content = null ) { |
| 27 |
$this->views( 'shortcodes/reading-time' ); |
| 28 |
} |
| 29 |
|
| 30 |
public function view_params() { |
| 31 |
$single_doc_content = $this->attributes['the_content']; |
| 32 |
$content_without_html_tags = strip_tags( $single_doc_content ); |
| 33 |
preg_match_all( '/<[^>]*>|[\p{L}\p{M}]+/u', $content_without_html_tags, $matches ); |
| 34 |
$reading_total_words = ! empty( $matches[0] ) ? count( $matches[0] ) : count( [] ); |
| 35 |
|
| 36 |
//lets assume an adult reads 200 words per minute, based on this information calculate the reading time |
| 37 |
$minutes = floor( $reading_total_words / 200 ); |
| 38 |
$seconds = floor( $reading_total_words % 200 / ( 200 / 60 ) ); |
| 39 |
$minutes = $minutes != 0 && $seconds >= 30 ? ( $minutes + 1 ) : ( $minutes != 0 && $minutes != 1 && $seconds < 30 ? ( $minutes - 1 ) : ( $minutes == 1 ? $minutes : '< ' . 1 ) ); |
| 40 |
$post_id = get_the_ID(); |
| 41 |
|
| 42 |
$est_reading_text = ! empty( get_post_meta( $post_id, '_betterdocs_est_reading_text', true ) ) ? get_post_meta( $post_id, '_betterdocs_est_reading_text', true ) : ''; |
| 43 |
$calculate_time = $minutes . ' ' . ( (int) $minutes <= 1 ? $this->attributes['singular_reading_text'] : $this->attributes['reading_text'] ); |
| 44 |
$calculate_time = ! empty( $est_reading_text ) ? $est_reading_text : $calculate_time; |
| 45 |
|
| 46 |
return [ |
| 47 |
'reading_title' => $this->attributes['reading_title'], |
| 48 |
'time' => $calculate_time |
| 49 |
]; |
| 50 |
} |
| 51 |
} |
| 52 |
|