Skip to content

Instantly share code, notes, and snippets.

@ajskelton
Last active May 28, 2022 14:13
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save ajskelton/7ef351167f8c8eb22514faf6e4374e37 to your computer and use it in GitHub Desktop.
Save ajskelton/7ef351167f8c8eb22514faf6e4374e37 to your computer and use it in GitHub Desktop.
Add a Number field to the WordPress Customizer.
$wp_customize->add_setting( 'themeslug_number_setting_id', array(
'capability' => 'edit_theme_options',
'sanitize_callback' => 'themeslug_sanitize_number_absint',
'default' => 1,
) );
$wp_customize->add_control( 'themeslug_number_setting_id', array(
'type' => 'number',
'section' => 'custom_section', // Add a default or your own section
'label' => __( 'Custom Number' ),
'description' => __( 'This is a custom number.' ),
) );
function themeslug_sanitize_number_absint( $number, $setting ) {
// Ensure $number is an absolute integer (whole number, zero or greater).
$number = absint( $number );
// If the input is an absolute integer, return it; otherwise, return the default
return ( $number ? $number : $setting->default );
}
@manchumahara
Copy link

the sanitizer function themeslug_sanitize_number_absint doesn't allow to save zero due to the last line

return ( $number ? $number : $setting->default );

@ayoubkhan558-zz
Copy link

you can also use 'absint' as 'sanitize_callback'

'sanitize_callback' => 'absint',

also you can use custom attributes with this

'input_attrs' => array(
    'min' => 1,
    'max' => 10
)

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