Skip to content

Commit 680199e

Browse files
committed
0 parents  commit 680199e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Function.HTML-Build-Attributes.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
if ( ! function_exists('html_build_attributes') ) :
4+
5+
/**
6+
* Generate a string of HTML attributes
7+
*
8+
* @param array $attr Associative array of attribute names and values.
9+
* @param callable $callback Callback function to escape values for HTML attributes.
10+
* Defaults to the WordPress' 'esc_attr' function.
11+
* @return string Returns a string of HTML attributes.
12+
*/
13+
function html_build_attributes( $attr = [], $callback = 'esc_attr' )
14+
{
15+
$html = '';
16+
17+
if ( count($attr) ) {
18+
$html = array_map(
19+
function ( $val, $key ) {
20+
if ( is_bool( $val ) ) {
21+
return ( $val ? $key : '' );
22+
} elseif ( isset( $val ) ) {
23+
if ( is_array( $val ) ) {
24+
$val = implode( ' ', $val );
25+
}
26+
27+
if ( is_callable( $callback ) ) {
28+
$val = call_user_func( $callback, $val );
29+
}
30+
31+
return sprintf( '%1$s="%2$s"', $key, $val );
32+
}
33+
},
34+
$attr,
35+
array_keys( $attr )
36+
);
37+
38+
$html = implode( ' ', $html );
39+
}
40+
41+
return $html;
42+
}
43+
44+
endif;

0 commit comments

Comments
 (0)