estimated-reading-time.php
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* CPAC_Column_Post_Estimated_Reading_Time
*
* @since 2.3.3
*/
class CPAC_Column_Post_Estimated_Reading_Time extends CPAC_Column {
/**
* @see CPAC_Column::init()
* @since 2.3.3
*/
public function init() {
parent::init();
// Properties
$this->properties['type'] = 'column-estimated_reading_time';
$this->properties['label'] = __( 'Estimated Reading Time', 'codepress-admin-columns' );
// Options
$this->options['words_per_minute'] = 200;
}
/**
* Estimate read time in readable format
*
* @see CPAC_Column::get_value()
* @since 2.3.3
*/
public function get_value( $post_id ) {
return $this->convert_seconds_to_readable_time( $this->get_raw_value( $post_id ) );
}
/**
* Estimate read time in seconds
*
* @see CPAC_Column::get_raw_value()
* @since 2.3.3
*/
public function get_raw_value( $post_id ) {
return $seconds = $this->get_estimated_reading_time_in_seconds( get_post_field( 'post_content', $post_id ) );
}
/**
* @since 2.3.3
*/
public function convert_seconds_to_readable_time( $seconds ) {
$time = '—';
if ( $seconds ) {
$minutes = floor( $seconds / 60 );
$seconds = floor( $seconds % 60 );
$time = $minutes;
if ( $seconds < 10 ) {
$seconds = '0' . $seconds;
}
if ( '00' != $seconds ) {
$time .= ':' . $seconds;
}
if ( $minutes < 1 ) {
$time = $seconds . ' ' . _n( 'second', 'seconds', $seconds, 'codepress-admin-columns' );
}
else {
$time .= ' ' . _n( 'minute', 'minutes', $minutes, 'codepress-admin-columns' );
}
}
return $time;
}
/**
* @since 2.3.3
*/
public function get_estimated_reading_time_in_seconds( $content ) {
$word_count = $this->str_count_words( $this->strip_trim( $content ) );
if ( ! $word_count ) {
return 0;
}
return (int) floor( ( $word_count / $this->options->words_per_minute ) * 60 );
}
/**
* @see CPAC_Column::apply_conditional()
* @since 2.3.3
*/
public function apply_conditional() {
if ( post_type_supports( $this->storage_model->key, 'editor' ) ) {
return true;
}
return false;
}
/**
* @since 2.3.3
*/
public function display_settings() {
$field_key = 'words_per_minute';
$label = __( 'Words per minute', 'codepress-admin-columns' );
$description = __( 'Estimated reading time in words per minute', 'codepress-admin-columns' );
?>
<tr class="column_<?php echo $field_key; ?>">
<?php $this->label_view( $label, $description, $field_key ); ?>
<td class="input">
<input type="text" name="<?php $this->attr_name( $field_key ); ?>" id="<?php $this->attr_id( $field_key ); ?>" value="<?php echo $this->options->words_per_minute; ?>"/>
</td>
</tr>
<?php
}
}