In this short tutorial, we are going to add to the Customizer, the ability to change the color of a Scalable Vector Graphics (SVG).

# SVG.

SVG is an image format, so you can use it inside an <img> tag in HTML.

<img src="magnifier.svg" alt="Magnifier glass">

Or as a background-image in CSS.

.bg-img {
  background: url(magnifier.svg);
}

But you will just obtain an image, without the ability to change it’s color(s) or to modify it’s inner code if needed.

Magnifier glass
magnifier.svg

# The challenge !

I had to deal with this particular issue in my Full Screen Morphing Search plugin.
Let’s first take a look at the code inside this SVG.

<?xml version="1.0" encoding="iso-8859-1"?>
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 viewBox="0 0 56.966 56.966" style="enable-background:new 0 0 56.966 56.966;" xml:space="preserve">
<path fill="#ddd" d="M55.146,51.887L41.588,37.786c3.486-4.144,5.396-9.358,5.396-14.786c0-12.682-10.318-23-23-23s-23,10.318-23,23
	s10.318,23,23,23c4.761,0,9.298-1.436,13.177-4.162l13.661,14.208c0.571,0.593,1.339,0.92,2.162,0.92
	c0.779,0,1.518-0.297,2.079-0.837C56.255,54.982,56.293,53.08,55.146,51.887z M23.984,6c9.374,0,17,7.626,17,17s-7.626,17-17,17
	s-17-7.626-17-17S14.61,6,23.984,6z"/>
</svg>

If you copy and paste this pretty ugly bunch of code inside an HTML block of a php file in WordPress, you’ll get some nice errors about allowed HTML tags and security output…

# Allow SVG tags !

Using 'wp_kses_allowed_html' hook, we can expand the list of allowed HTML tags.

if ( ! function_exists( 'full_screen_morphing_search_add_svg_tags' ) ) {
/**
* Function to add svg tags to wp_kses_allowed_html
*
* @param array $svg_tags The SVG Tags.
*/
function full_screen_morphing_search_add_svg_tags( $svg_tags ) {
	$svg_tags['svg']  = array(
		'version'     => true,
		'id'          => true,
		'xmlns'       => true,
		'xmlns:xlink' => true,
		'x'           => true,
		'y'           => true,
		'viewbox'     => true, // <= Must be lower case !
		'style'       => true,
		'xml:space'   => true,
	);
	$svg_tags['path'] = array(
		'fill' => true,
		'd'    => true,
		);
	return $svg_tags;
}
add_filter( 'wp_kses_allowed_html', 'full_screen_morphing_search_add_svg_tags' );
}

# Retrieve the SVG !

Now we can get the SVG into the HTML of our php file.
But to do so, we need to do it the WordPress way.
Since SVG is an XML file, we need to grab it’s content to display it in the desired place/location.
To do so, we use the wp_remote_get() function.

<button id="morphsearch-submit" class="morphsearch-submit" type="submit">
	<?php
    // The only required parameter is the $url to the file.
	$response = wp_remote_get( 'https://plugins.svn.wordpress.org/full-screen-morphing-search/trunk/assets/img/magnifier.svg' );
	if ( is_array( $response ) AND ! is_wp_error( $response ) ) {
        // The response body.		
        echo wp_kses( $response['body'], 'full_screen_morphing_search_add_svg_tags' ); // Use the content.
	}
	?>
</button>

Line 5 – Replace AND by && (wrong output in the code).
Line 7 – The body of our SVG file is getting called, using the earlier function to allow SVG tags, wrapped by wp_kses() to securely output the content.

# The Customizer

Now, for the Customizer part, you could do it in different ways.
I’ll share here how I’ve did it for my plugin.
Generally speaking, the steps would be :
1- Create a Panel, a Section, a Setting and a Control.
OR
1- Create a Section, a Setting and a Control.
THEN
2- Enqueue and Localize a JS file using the ‘wp-head’ hook (to output generated CSS) with a 'jquery' dependency.
3- Enqueue another JS file using the ‘customize_preview_init’ hook (to control live preview) with two dependencies 'jquery', 'customize-preview'.
4- Pass php variables to the localized JS file.
5- Output the default, or changed, value of our Setting/Control from the localized JS file.
6- Make Customizer preview reload changes asynchronously from the second JS file.
7- That’s it ! 🙂


1- Since it’s a plugin I’m using the option type for the Setting.
Also note that I’m using 'transport' => 'postMessage' .

<?php
/**
 * Add our Customizer content.
 *
 * @param WP_Customize_Manager $wp_customize Manager instance.
 */
function full_screen_morphing_search_customize_register( $wp_customize ) {

	// Add FSMS Plugin Panel.
	$wp_customize->add_panel(
		'fsmsp_panel',
		array(
			'title'    => __( 'FSMS Plugin', 'full-screen-morphing-search' ),
			'priority' => 160,
		)
	);

	// Add Color Section.
	$wp_customize->add_section(
		'fsmsp_color',
		array(
			'title'    => __( 'FSMS Colors', 'full-screen-morphing-search' ),
			'priority' => 5,
			'panel'    => 'fsmsp_panel',
		)
	);

	// ================================
	// = FSMS Magnifier Submit Color. =
	// ================================
	$wp_customize->add_setting(
		'fsmsp_options[fsmsp_magnifier_submit_color]',
		array(
			'default'           => '#ddd',
			'sanitize_callback' => 'sanitize_hex_color',
			'capability'        => 'edit_theme_options',
			'type'              => 'option',
			'transport'         => 'postMessage',

		)
	);

	$wp_customize->add_control(
		new WP_Customize_Color_Control(
			$wp_customize,
			'fsmsp_options[fsmsp_magnifier_submit_color]',
			array(
				'label'       => __( 'FSMS Magnifier Submit Color', 'full-screen-morphing-search' ),
				'description' => esc_attr__( 'Change the magnifier submit  color', 'full-screen-morphing-search' ),
				'section'     => 'fsmsp_color',
				'settings'    => 'fsmsp_options[fsmsp_magnifier_submit_color]',
			)
		)
	);
}
add_action( 'customize_register', 'full_screen_morphing_search_customize_register' );

2- Remember that it’s a plugin, I’ve already added the action in the __contruct() fuction :

if ( ! is_admin() ) {
    add_action( 'wp_head', array( $this, 'full_screen_morphing_search_enqueue_js' ) );
}

So our enqueue and localize would look like :

<?php
/**
 * Loads JS used for this plugin.
 */
public function full_screen_morphing_search_enqueue_js() {

	// Require WordPress jQuery.
	wp_enqueue_script( 'jquery' );

	// Load Javascript.
	wp_enqueue_script( $this->plugin->name, $this->plugin->url . 'assets/js/full-screen-morphing-search.js', array( 'jquery' ), '1.0', true );

	// Associative Array 'fsmsp_options'.
	$fsmsp_options = get_option( 'fsmsp_options' );

	// Declare PHP Variables to be passed to JS.
	// This is to test if the fsmsp_options index does not exist in the options table of our db.
	$fsmsp_options_does_not_exists = ( null === get_option( 'fsmsp_options', null ) ) ? true : false;

	// Localize full-screen-morphing-search.js !
	wp_localize_script(
		$this->plugin->name,
		'fsmsp_vars',
		array(
			'fsmsp_options_does_not_exists' => $fsmsp_options_does_not_exists,
             // The following one is to output the changed or default value of our Setting/Control.
			'fsmsp_magnifier_submit_color'  => esc_attr( ( ! empty( $fsmsp_options['fsmsp_magnifier_submit_color'] ) ? $fsmsp_options['fsmsp_magnifier_submit_color'] : '#ddd' ) ),
		)
	);

}

3- As you can read in the description of the following function, it’s useless if your settings aren’t using 'transport' => 'postMessage' instead of the default 'transport' => 'refresh'.

<?php
/**
 * This outputs the javascript needed to automate the live settings preview.
 * Also keep in mind that this function isn't necessary unless your settings
 * are using 'transport'=>'postMessage' instead of the default 'transport'
 * => 'refresh'.
 *
 * Used by hook: 'customize_preview_init'
 */
function fsmsp_customize_preview_js() {
	$handle    = 'fsmsp-customize-preview';
	$src       = plugins_url( 'assets/js/customize-preview.js', __FILE__ );
	$deps      = array( 'jquery', 'customize-preview' );
	$ver       = '0.1';
	$in_footer = true;
	wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
}
add_action( 'customize_preview_init', 'fsmsp_customize_preview_js' );


4- & 5- Pass php variables & Output the default, or changed, value of our Setting/Control from the localized JS file.

( function( $ ) {

	// Output default option's value !
	if ( fsmsp_vars.fsmsp_options_does_not_exists ) {
		// Output fsmsp_magnifier_submit_color.
		$( '#Capa_1 path' ).css( 'fill', '#ddd' );
	}
	// Output changed optionn's value !
	else {
		$( '#Capa_1 path' ).css( 'fill', fsmsp_vars.fsmsp_magnifier_submit_color );
	}

} )( jQuery );

6- Make Customizer preview reload changes asynchronously from the second JS file.

( function( $ ) {

	// FSMS Magnifier Submit Color.
	wp.customize( 'fsmsp_options[fsmsp_magnifier_submit_color]', function( value ) {
		value.bind( function( newval ) {
			$( '#Capa_1 path' ).css( 'fill', newval );
		} );
	} );

} )( jQuery );

That’s it ! you’re done 🙂
Open the Customizer and play with you’re new shinny control 😉
Once a newvalcolor chosen, publish and check it out on the live site.

Hope that this short tutorial will give you some ideas for your next project.
If you found an error or have a question, don’t hesitate, comments are opened 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.