1 <?php
2
3 /**
4 * Color picker field which submits a 6-character hex code with the hash mark.
5 *
6 * Provides an interface to navigate colors and submits the 6-character hex code
7 * e.g. `#ffffff`. This field uses the
8 * {@link https://make.wordpress.org/core/2012/11/30/new-color-picker-in-wp-3-5/
9 * WordPress core color picker introduced in WordPress 3.5}.
10 *
11 * @package Fieldmanager_Field
12 */
13 class Fieldmanager_Colorpicker extends Fieldmanager_Field {
14
15 /**
16 * Override field_class.
17 *
18 * @var string
19 */
20 public $field_class = 'colorpicker';
21
22 /**
23 * Static variable so we only load static assets once.
24 *
25 * @var boolean
26 */
27 public static $has_registered_statics = false;
28
29 /**
30 * Build the colorpicker object and enqueue assets.
31 *
32 * @param string $label
33 * @param array $options
34 */
35 public function __construct( $label = '', $options = array() ) {
36 if ( ! self::$has_registered_statics ) {
37 add_action( 'admin_enqueue_scripts', function() {
38 wp_enqueue_style( 'wp-color-picker' );
39 } );
40 fm_add_script( 'fm_colorpicker', 'js/fieldmanager-colorpicker.js', array( 'jquery', 'wp-color-picker' ), '1.0', true );
41 self::$has_registered_statics = true;
42 }
43
44 $this->sanitize = array( $this, 'sanitize_hex_color' );
45
46 parent::__construct( $label, $options );
47 }
48
49 /**
50 * Form element.
51 *
52 * @param mixed $value
53 * @return string HTML
54 */
55 public function form_element( $value = '' ) {
56 return sprintf(
57 '<input class="fm-element fm-colorpicker-popup" name="%1$s" id="%2$s" value="%3$s" %4$s />',
58 esc_attr( $this->get_form_name() ),
59 esc_attr( $this->get_element_id() ),
60 esc_attr( $value ),
61 $this->get_element_attributes()
62 );
63 }
64
65 /**
66 * Sanitizes a hex color.
67 *
68 * Returns either '', a 3 or 6 digit hex color (with #), or nothing.
69 *
70 * This was copied from core; sanitize_hex_color() is not available outside
71 * of the customizer. {@see https://core.trac.wordpress.org/ticket/27583}.
72 *
73 * @param string $color
74 * @return string
75 */
76 function sanitize_hex_color( $color ) {
77 $color = trim( $color );
78
79 if ( '' !== $color && preg_match( '|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
80 return $color;
81 }
82
83 return '';
84 }
85 }
86