class-kirki-scripts-icons.php (2493B)
1 <?php 2 /** 3 * Try to automatically generate the script necessary for adding icons to panels & section 4 * 5 * @package Kirki 6 * @category Core 7 * @author Aristeides Stathopoulos 8 * @copyright Copyright (c) 2016, Aristeides Stathopoulos 9 * @license http://opensource.org/licenses/https://opensource.org/licenses/MIT 10 * @since 2.0 11 */ 12 13 // Exit if accessed directly. 14 if ( ! defined( 'ABSPATH' ) ) { 15 exit; 16 } 17 18 if ( ! class_exists( 'Kirki_Scripts_Icons' ) ) { 19 20 /** 21 * Adds scripts for icons in sections & panels. 22 */ 23 class Kirki_Scripts_Icons { 24 25 /** 26 * The script generated for ALL fields 27 * 28 * @static 29 * @access public 30 * @var string 31 */ 32 public static $icons_script = ''; 33 34 /** 35 * Whether the script has already been added to the customizer or not. 36 * 37 * @static 38 * @access public 39 * @var bool 40 */ 41 public static $script_added = false; 42 43 /** 44 * The class constructor 45 */ 46 public function __construct() { 47 add_action( 'customize_controls_print_footer_scripts', array( $this, 'enqueue_script' ), 99 ); 48 } 49 50 /** 51 * This works on a per-field basis. 52 * Once created, the script is added to the $icons_script property. 53 * 54 * @static 55 * @access public 56 * @param array $args The field definition. 57 * @return void 58 */ 59 public static function generate_script( $args = array() ) { 60 61 // If "icon" is not specified then no need to proceed. 62 if ( ! isset( $args['icon'] ) || '' === $args['icon'] ) { 63 return; 64 } 65 66 // If the panel or section ID is not defined then early exit. 67 if ( ! isset( $args['id'] ) ) { 68 return; 69 } 70 71 $element = '#accordion-panel-' . $args['id'] . ' > h3, #accordion-panel-' . $args['id'] . ' .panel-title'; 72 if ( false !== strpos( $args['icon'], 'dashicons' ) ) { 73 $args['icon'] = 'dashicons ' . $args['icon']; 74 } 75 76 $script = '$("' . $element . '").prepend(\'<span class="' . esc_attr( $args['icon'] ) . '" style="vertical-align:text-bottom"></span> \');'; 77 78 if ( false === strpos( self::$icons_script, $script ) ) { 79 self::$icons_script .= $script; 80 } 81 82 } 83 84 /** 85 * Format the script in a way that will be compatible with WordPress. 86 */ 87 public function enqueue_script() { 88 if ( ! self::$script_added && '' !== self::$icons_script ) { 89 self::$script_added = true; 90 // @codingStandardsIgnoreStart 91 echo '<script>jQuery(document).ready(function($) { "use strict"; ' . self::$icons_script . '});</script>'; 92 // @codingStandardsIgnoreEnd 93 } 94 } 95 } 96 }