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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
<?php
abstract class CMB2_Type_Counter_Base extends CMB2_Type_Base {
public $has_counter = false;
public function char_counter_markup( $val ) {
$markup = '';
if ( ! $this->field->args( 'char_counter' ) ) {
return $markup;
}
$type = (string) $this->field->args( 'char_counter' );
$field_id = $this->_id( '', false );
$char_max = (int) $this->field->prop( 'char_max' );
if ( $char_max ) {
$char_max = 'data-max="' . $char_max . '"';
}
switch ( $type ) {
case 'words':
$label = $char_max
? $this->_text( 'words_left_text', esc_html__( 'Words left', 'cmb2' ) )
: $this->_text( 'words_text', esc_html__( 'Words', 'cmb2' ) );
break;
default:
$type = 'characters';
$label = $char_max
? $this->_text( 'characters_left_text', esc_html__( 'Characters left', 'cmb2' ) )
: $this->_text( 'characters_text', esc_html__( 'Characters', 'cmb2' ) );
break;
}
$msg = $char_max
? sprintf( '<span class="cmb2-char-max-msg">%s</span>', $this->_text( 'characters_truncated_text', esc_html__( 'Your text may be truncated.', 'cmb2' ) ) )
: '';
$length = strlen( $val );
$width = $length > 1 ? ( 8 * strlen( (string) $length ) ) + 15 : false;
$markup .= '<p class="cmb2-char-counter-wrap">';
$markup .= sprintf(
'<label><span class="cmb2-char-counter-label">%2$s:</span> <input id="%1$s" data-field-id="%3$s" data-counter-type="%4$s" %5$s class="cmb2-char-counter" type="text" value="%6$s" readonly="readonly" style="%7$s"></label>%8$s',
esc_attr( 'char-counter-' . $field_id ),
$label,
esc_attr( $field_id ),
$type,
$char_max,
$length,
$width ? "width: {$width}px;" : '',
$msg
);
$markup .= '</p>';
$this->field->add_js_dependencies( array(
'word-count',
'wp-util',
'cmb2-char-counter',
) );
$this->has_counter = true;
return $markup;
}
public function maybe_update_attributes_for_char_counter( $attributes ) {
$char_counter = $this->char_counter_markup( $attributes['value'] );
if ( $char_counter ) {
$attributes['class'] = ! empty( $attributes['class'] ) ? $attributes['class'] . ' cmb2-count-chars' : ' cmb2-count-chars';
$max = $this->enforce_max();
if ( $max ) {
$attributes['maxlength'] = $max;
}
$attributes['desc'] = $char_counter . $attributes['desc'];
}
return $attributes;
}
public function enforce_max() {
$char_max = (int) $this->field->args( 'char_max' );
return ( $this->field->args( 'char_max_enforce' ) && $char_max > 0
&& 'words' !== $this->field->args( 'char_counter' ) )
? $char_max
: false;
}
}