Make WordPress Core

Opened 9 years ago

Last modified 5 years ago

#32192 new enhancement

Add HTML attribute builder helper function

Reported by: paulwilde's profile paulwilde Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.2.1
Component: General Keywords: has-patch
Focuses: Cc:

Description

I've seen (and wrote) a lot of plugins which manually build out each HTML attribute as a loop, escaping each value and then removing any attribute that has no value. Wouldn't it be nice if there was a function that does all that for you?

This patch introduces a new function html_attributes which accepts an array and builds out a string of attributes whilst sanitising the values and removing any empty attributes.

I've also updated any uses in core removing the logic and using the function instead. There's probably a few instances still left to update, but this is a good start.

Attachments (5)

html-attributes.diff (7.4 KB) - added by paulwilde 9 years ago.
html-attributes.2.diff (5.9 KB) - added by paulwilde 9 years ago.
html-attributes.3.diff (5.9 KB) - added by paulwilde 9 years ago.
Fixed a bug in the previous patch.
html-attributes.4.diff (6.0 KB) - added by paulwilde 9 years ago.
html-attributes.5.diff (7.1 KB) - added by paulwilde 9 years ago.

Download all attachments as: .zip

Change History (12)

@paulwilde
9 years ago

Fixed a bug in the previous patch.

#2 @jdgrimes
9 years ago

Since you check is_array( $attrs ), is it still necessary to do (array) $attrs in the loop?

Also, shouldn't src use esc_url() instead like for href?

#3 @paulwilde
9 years ago

  • Keywords has-patch added

Valid points.

I've attached an updated patch.

#4 @SergeyBiryukov
9 years ago

#29479 was marked as a duplicate.

#5 follow-up: @azaozz
9 years ago

I'm actually not sure this is a good idea. Look at how unreadable submit_button() and get_submit_button() can be in some cases... Frankly I don't see any advantage in having them. Just one more thing to look up while trying to read the code.

The same applies for the HTML attributes. In addition having the escape functions in there means some things will be double escaped and some things will not be escaped properly.

#6 @paulwilde
9 years ago

Attached an updated patch with 2 more instances of attribute building. One inside wp_video_shortcode() and the other inside new WP_Customize_Control()->input_attrs().

#7 in reply to: ↑ 5 @jdgrimes
9 years ago

Replying to azaozz:

The same applies for the HTML attributes. In addition having the escape functions in there means some things will be double escaped and some things will not be escaped properly.

Escaping twice may make the site do extra work, but double-escaping isn't a concern as far a breaking things since these functions won't actually add an extra layer of escaping when called twice.

Note: See TracTickets for help on using tickets.