Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Last active February 28, 2022 03:30
Show Gist options
  • Save jtsternberg/c09f5deb7d818d0d170b to your computer and use it in GitHub Desktop.
Save jtsternberg/c09f5deb7d818d0d170b to your computer and use it in GitHub Desktop.
CMB2 Number Field
<?php
$cmb->add_field( array(
'name' => __( 'Postive numbers', 'theme-domain' ),
'desc' => __( 'Numbers only', 'msft-newscenter' ),
'id' => $prefix . 'number',
'type' => 'text',
'attributes' => array(
'type' => 'number',
'pattern' => '\d*',
),
'sanitization_cb' => 'absint',
'escape_cb' => 'absint',
) );
$cmb->add_field( array(
'name' => __( 'Numbers', 'theme-domain' ),
'desc' => __( 'Numbers only', 'msft-newscenter' ),
'id' => $prefix . 'number',
'type' => 'text',
'attributes' => array(
'type' => 'number',
'pattern' => '\d*',
),
'sanitization_cb' => 'intval',
'escape_cb' => 'intval',
) );
@xlplugins
Copy link

xlplugins commented Mar 13, 2018

Hi,
I am unable to add default value using this method.
CMB2 version: 2.3.0

When I input any default param as 'default' => 55 then escape_cb function converts it to 0. As CMB2 returns escaped value in CMB2_Field::escaped_value(); function and do not consider default value before running escape_cb.

Unable to understand if this is something intentional or a bug in CMB2. A workaround is to use custom escape_cb and handle the scenario.

Thanks.

@unaibamir
Copy link

working beautifully!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment