LoginSignup
1
0

More than 5 years have passed since last update.

WordpressのカスタマイズTips:カスタマイザーでスライダーを利用する

Posted at

WordPressのテーマカスタマイザーでスライダーを表示する方法です。
参考ページ:https://premium.wpmudev.org/blog/wordpress-theme-customizer-guide/

WP_Customize_Controlを拡張して、独自のUI(スライダー)を作成する

  • WP_Customize_Controlを拡張したWP_Customize_Rangeを作成
  • パラメータで「min:最小値」「max:最大値」「step:ステップ」を渡せる
if( class_exists( 'WP_Customize_Control' ) ) {
    class WP_Customize_Range extends WP_Customize_Control {
        public $type = 'range';

        public function __construct( $manager, $id, $args = array() ) {
            parent::__construct( $manager, $id, $args );
            $defaults = array(
                'min' => 0,
                'max' => 10,
                'step' => 1
            );
            $args = wp_parse_args( $args, $defaults );

            $this->min = $args['min'];
            $this->max = $args['max'];
            $this->step = $args['step'];
        }

        public function render_content() {
        ?>
        <label>
            <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
            <input class='range-slider' min="<?php echo $this->min ?>" max="<?php echo $this->max ?>" step="<?php echo $this->step ?>" type='range' <?php $this->link(); ?> value="<?php echo esc_attr( $this->value() ); ?>" oninput="jQuery(this).next('input').val( jQuery(this).val() )">
            <input onKeyUp="jQuery(this).prev('input').val( jQuery(this).val() )" type='text' value='<?php echo esc_attr( $this->value() ); ?>'>

        </label>
        <?php
        }
    }
}

カスタマイザーのセッティング、コントローラーを追加

  • add_setting, add_controlでセッティングとコントローラーを作成
  • add_controlで、UI部品にオリジナルのWP_Customize_Rangeを指定
  • パラメータで、最小値、最大値、ステップを指定
  • 以下のサンプルコードの場合、label、sectionは環境に合わせて適当に
$wp_customize->add_setting( 'customizable_range' , array(
    'default'     => 15,
    'type' => 'theme_mod'
  ) 
);

$wp_customize->add_control(
  new WP_Customize_Range(
    $wp_customize,
    'ctrl_customizable_range',
    array(
      'label'   => 'ラベル',
      'min' => 10,
      'max' => 20,
      'step' => 1,
      'section' => 'my_section',
      'settings'   => 'customizable_range',
    )
  )
);

出力は通常のWP_Customize_Control部品と同様に

  • スライダーの値はge_theme_mod()でアクセス可能
  • 出力時のデフォルト値は、セッティングのデフォルト値とは別途必要
<div id='photocount'>
    <span><?php echo get_theme_mod( 'customizable_range', 15 ) ?></span> photos
</div>

という感じで、カスタマイザーでスライダーを使うことができました。
フォントサイズを可変に…といった場面で利用できます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0