0

I have the following Customizer control/settings to control an image's opacity:

// Image Opacity
$wp_customize->add_setting( 'image_opacity', array(
    'default'           => '1.000',
    'sanitize_callback' => 'my_theme_sanitize_number_range'
) );
$wp_customize->add_control( 'image_opacity', array(
    'label'             => __( 'Image Opacity', 'my-theme' ),
    'type'              => 'range',
    'input_attrs'       => array(
        'min'           => 0,
        'max'           => 1.000,
        'step'          => 0.001,
    ),
) );

and the following sanitize function:

// Sanitize Number Range
function my_theme_sanitize_number_range( $number, $setting ) {
    $number = absint( $number );
    $atts = $setting->manager->get_control( $setting->id )->input_attrs;
    $min = ( isset( $atts['min'] ) ? $atts['min'] : $number );
    $max = ( isset( $atts['max'] ) ? $atts['max'] : $number );
    $step = ( isset( $atts['step'] ) ? $atts['step'] : 0.001 );
    return ( $min <= $number && $number <= $max && is_int( $number / $step ) ? $number : $setting->default );
}

It works fine for whole numbers, like if 'max' => 1, and 'step' => 1 but I want the steps to three decimal points like 'step' => 0.001, which doesn't work.

How do I accomplish this?

0

you need to remove the call of absint at beginning. you should do more debugging to avoid this mistake.

after that the division $number / $step always returns a float. then to round the value, use something like that :

$number = floor($number / $atts['step']) * $atts['step'];

return ( $min <= $number && $number <= $max ) ? $number : $setting->default;
  • unfortunately that does not work – Troy Templeman Aug 12 '18 at 1:33
  • you need to remove the call of absint at beginning. – Kaperto Aug 12 '18 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.