Search code examples
phpwordpressescapingechowordpress-plugin-creation

Escape when echoed


I've been trying to submit a plugin for review and I keep having problems with the echo line. The last version I sent was like this.

<option value="">
    <?php _e( '- Default', MF_TEXT_DOMAIN ); ?>
</option>
<?php foreach ( $folders as $folder ) {
    $folder = trim( $folder );
    $folder = esc_attr( $folder );
    echo "<option value=\"{$folder}\">{$folder}</option>";
} ?>

And the WordPress response was:

This is not escaped:

echo "<option value=\"{$folder}\">{$folder}</option>";

$folder MUST be escaped when it's echo'd.

Now I'm ready to submit the code for review again but first I want to make sure I'm correct.

Here the new code

<option value="">
    <?php _e( '- Default', MF_TEXT_DOMAIN ); ?>
</option>
<?php foreach ( $folders as $folder ) {
    $folder = trim( $folder );
    echo '<option value="' . esc_attr( $folder ) . '">' . esc_attr( $folder ) . '</option>';
} ?>

I'd be very grateful if someone could help, as I'm a bit confused about the (escaped).


Solution

  • According to the developer documents, everything must be escaped for security reasons. Here are the escaping function WordPress provides for different data:

    esc_attr()      // Use on everything else that’s printed into an HTML element’s attribute.
    esc_html()      // Use anytime an HTML element encloses a section of data being displayed. This WILL NOT display HTML content, it is meant for being used inside HTML and will remove your HTML.
    esc_js()        // Use for inline Javascript.
    esc_textarea()  // Use this to encode text for use inside a textarea element.
    esc_url()       // Use on all URLs, including those in the src and href attributes of an HTML element.
    esc_url_raw()   // Use when storing a URL in the database or in other cases where non-encoded URLs are needed.
    wp_kses()       // Use to safely escape for all non-trusted HTML (post text, comment text, etc.)
    wp_kses_post()  // Alternative version of wp_kses() that automatically allows all HTML that is permitted in post content.
    wp_kses_data()  // Alternative version of wp_kses() that allows only the HTML permitted in post comments.
    

    Here is the official documentation if you want to read more into it.

    https://developer.wordpress.org/apis/security/escaping/