Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Last active February 28, 2022 03:30
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • 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',
) );
@claudiut
Copy link

Thanks for this!

@picard102
Copy link

I get "Wrong parameter count for intval()" when I try this.

@jb510
Copy link

jb510 commented Aug 8, 2017

TY!

Note: This really should be in the wiki as an example somewhere.

Edit: Found it at the bottom here: https://github.com/CMB2/CMB2/wiki/Tips-&-Tricks and https://cmb2.io/docs/tips-&-tricks but couldn't find it search either of those docs directly...

@allysonsouza
Copy link

I'm having the same, Wrong parameter count for intval()

@allysonsouza
Copy link

allysonsouza commented Sep 17, 2017

I ended using this verification to see if is a numeric value and return an int:

function sanitize_int( $value, $field_args, $field ) {
	// Don't keep anything that's not numeric
	if ( ! is_numeric( $value ) ) {
		$sanitized_value = '';
	} else {
		// Ok, let's clean it up.
		$sanitized_value = absint( $value );
	}
	return $sanitized_value;
}

@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