WordPress Customizer – Range Control with Selected Value Indicator
The WordPress customizer, formerly know as theme customizer allows administrator(s) and/or owner to customize and control the appearance of their WordPress powered website via an intuitive, click-and-drag interface.
The Customization API allows theme and plugin developers to customize and add controls to the “Appearance” → “Customize” admin screen.
In this tutorial, I won’t go over the steps on how to leverage or integrate customizer in your theme or plugin. Rather, i will be showing us how to create your own custom controls using a range input field as a case study.
By default, the customizer support all type of input fields including “range”. My gripe with the range
input field is the lack of an indicator to show the current selected value. And this isn’t going to change anytime soon as the idea was rejected by WordPress core team.
I am not going to explain or step us through how the code work. Otto has that covered already.
Below is the PHP class for the range control.
class WP_Customize_Range_Control extends WP_Customize_Control public $type = 'custom_range'; public function enqueue() wp_enqueue_script( 'cs-range-control', 'path/to/range-control.js', array('jquery'), false, true ); public function render_content() ?> <label> if ( ! empty( $this->label )) : ?> <span class="customize-control-title"> echo esc_html($this->label); ?></span> endif; ?> <div class="cs-range-value"> echo esc_attr($this->value()); ?></div> <input data-input-type="range" type="range" $this->input_attrs(); ?> value=" echo esc_attr($this->value()); ?>" $this->link(); ?> /> if ( ! empty( $this->description )) : ?> <span class="description customize-control-description"> echo $this->description; ?></span> endif; ?> </label> |
And here is the JavaScript for range-control.js
(function ($) { $(document).ready(function ($) { $('input[data-input-type]').on('input change', function () { var val = $(this).val(); $(this).prev('.cs-range-value').html(val); $(this).val(val); }); }) })(jQuery); |
Link to code on GitHub here
To use this range custom control class, add a control to your existing list of customizer controls like so:
$wp_customize->add_control( new WP_Customize_Range_Control( $wp_customize, 'content_font_size', array( 'label' => __('Font Size'), 'section' => 'section_id_to_use_here', 'settings' => 'content_font_size', 'description' => __('Measurement is in pixel.'), 'input_attrs' => array( 'min' => 10, 'max' => 80, ), ) |
La Fin!
0 comments:
Post a Comment