Last active
December 13, 2017 17:14
-
-
Save rumur/b9d69d6359b32da9e413e7e43b3bfb67 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Compiles html attributes for the entity. | |
* | |
* Example: | |
* $attributes = [ | |
* 'id' => 'content', | |
* 'data-number' => 23, | |
* 'class' => [ 'container', 'maina-page' ], | |
* 'style' => [ | |
* 'settings' => [ | |
* 'glue' => ';', | |
* ], | |
* 'color:' => '#fff' | |
* ] | |
* //... | |
* ]; | |
* | |
* The result is following: id="content" data-number="23" class="container main-page" style="color:#fff;" //... | |
* | |
* @param array $attributes | |
* | |
* @use esc_attr @see https://developer.wordpress.org/reference/functions/esc_attr/ | |
* | |
* @since v1.1 | |
* | |
* @author rumur | |
* | |
* @return string | |
*/ | |
function compile_attributes( array $attributes ) { | |
$compiled_attributes = ''; | |
foreach ( $attributes as $key => $a ) { | |
if ( is_array( $a ) ) { | |
$glue = " "; | |
// Get settings for the current iteration. | |
if ( array_key_exists( 'settings', $a ) ) { | |
extract( $a['settings'] ); | |
unset( $a['settings'] ); | |
} | |
/** | |
* Walk trough the array of the attributes | |
* and make them as a single string. | |
*/ | |
$a = array_reduce( array_keys( $a ), function ( $carry, $name ) use ( $a, $glue ) { | |
$attribute_value = $a[ $name ]; | |
$attribute_key = ! is_numeric( $name ) ? $name : ''; | |
return $carry . $attribute_key . $attribute_value . $glue; | |
} ); | |
} | |
if ( $a != '' ) { | |
$compiled_attributes .= sprintf( '%s="%s" ', $key, esc_attr( $a ) ); | |
} | |
} | |
return $compiled_attributes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment