With the cmb2 plugin I created a metabox with a textarea metafield this way:

function myprefix_register_metabox() {

  $prefix = 'myprefix_';

  $cmb = new_cmb2_box( array(
    'id'            => $prefix . 'metabox',
    'title'         => esc_html__( 'My Metabox', 'cmb2' ),
    'object_types'  => array( 'page' ),
  ) );

  $cmb->add_field( array(
    'name'            => esc_html__( 'Text Area for Code', 'cmb2' ),
    'id'              => $prefix . 'textarea_code',
    'type'            => 'textarea_code',
    'sanitization_cb' => 'my_sanitize_text_callback',
  ) );

}
add_action( 'cmb2_admin_init', 'myprefix_register_metabox' );

I use this callback function to sanitize the metafield content:

function my_sanitize_text_callback( $value, $field_args, $field ) {

    $value = htmlentities( html_entity_decode( $value, ENT_QUOTES ), ENT_QUOTES );

    return $value;
}

Everything works fine, but how can I view the content of the textarea stored in the db, with the converted entities html_entity_decode() in the edit screen in the admin panel, to get a more human readable text?

1 Answer
1

I have seen that CMB2 offers the possibility to create a custom escaping function with which the values are checked before they’re displayed. So I set the escape_cb parameter in the metafield this way:

  $cmb->add_field( array(
    'name'            => esc_html__( 'Text Area for Code', 'cmb2' ),
    'id'              => $prefix . 'textarea_code',
    'type'            => 'textarea_code',
    'sanitization_cb' => 'my_sanitize_text_callback',
    'escape_cb'       => 'my_escape_text_callback'
  ) );

Then I created the callback function for escaping, in order to convert HTML entities to their corresponding characters:

function my_escape_text_callback( $value, $field_args, $field ) {

    $escaped_value = html_entity_decode( $value, ENT_QUOTES );

    return $escaped_value;

}

Now it works great and in the edit screen in the admin panel I visualize the readable text.

Leave a Reply

Your email address will not be published. Required fields are marked *