Opened 7 weeks ago
Last modified 7 weeks ago
#62738 new enhancement
Proposal for format_atts()
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | Formatting | Keywords: | |
Focuses: | Cc: |
Description
I have used wpcf7_format_atts(), a simple function to format HTML attributes, in my Contact Form 7 plugin for many years. With this function, you can convert this complicated error-prone code:
echo '<input type="checkbox" name="' . esc_attr( $cb_name ) . '" value="' . esc_attr( $cb_value ) . '" checked="checked" />';
into the following readable clean coding:
echo sprintf( '<input %s />', wpcf7_format_atts( array( 'type' => 'checkbox', 'name' => $cb_name, 'value' => $cb_value, 'checked' => true, ) ) );
I'd like to suggest introducing the same functionality into WordPress core as format_atts()
.
Another reason for me to suggest this is that the Plugin Check plugin detects errors of WordPress.Security.EscapeOutput.OutputNotEscaped
despite the fact that attribute values are properly escaped with esc_attr()
. If this function becomes WordPress standard and the PCP recognizes that, I and other developers who use similar formatting function will be able to avoid the false-positive error.
Change History (2)
#2
@
7 weeks ago
@takayukister note also that this kind of work is ongoing with the HTML API and it’s planned to have HTMP templating: see #60229 and #50867.
In the meantime you can already use the HTML API to this effect.
<?php $input = new WP_HTML_Tag_Processor( “<input>” ); $input->next_tag(); $input->set_attribute( “type”, “checked” ); $input->set_attribute( “checked”, true ); … return $input->get_updated_html();
A benefit to using the HTML API is that you will get fully well-formed HTML, unlike in the previous example which includes a few examples of outdated norms for HTML.
FWIW,
OutputNotEscaped
is part of the WordPress Coding Standards project, so it's not unique to PCP. A static analysis tool just sees that you're usingecho
with some arbitrary string. It can't know whether the full string is safe or not, hence the warning.So it's not really a false positive that can be fixed. It's one of these instances where, if you know what you are doing, you can ignore the PHPCS warning.
Even if PHPCS would know about this new function, doing something like
echo sprintf( '<input %s />', ... )
would still give you anOutputNotEscaped
warning because of theecho
.So whether you use your own
wpcf7_format_atts()
function or a core-providedformat_atts()
function, this would not change.