0

From what I understand esc_attr_e is ideally used for escaping values in attributes - Is it right that the usage of esc_attr_e can also be worked in with non attribute values, such as the h3 and label elements in the example below?

<h3><?php esc_attr_e( 'Some Text', 'my-plugin' ); ?></h3>


<form name="myplugin_form" method="post" action="">

        <input type="hidden" name="myplugin_form_submitted" value="Y">

    <table class="form-table">
            <tr>
                <td><label for="ng_plugin_menu"><?php esc_attr_e( 'Plugin Menu Name', 'my-plugin' ); ?></label></td>
                <td><input name="ng_plugin_menu" id="ng_plugin_menu" type="text" value="<?php esc_attr_e ($my_plugin_label, 'my_plugin'); ?>" class="regular-text" placeholder="<?php esc_attr_e ('Placeholder Text', 'my_plugin'); ?>" /></td>
            </tr>

    </table>
    <p><input class="button-primary" type="submit" name="my_plugin_menu_submit" value="Save" /></p>

</form>

So using esc_attr_e it instead of _e, I was told by a senior developer that this is valid, but am looking for confirmation. It is also the purpose of my sample code that I want to allow translation for all strings.

3

I would suggest using esc_html instead of esc_attr for that, e.g.

<a href="<?php echo esc_url( $url );?>" class="<?php echo esc_attr( $classes ); ?>">
    <?php echo esc_html( $title ); ?>
</a>
<div>
    <?php echo wp_kses_post( $html_with_safe_tags );?>
</div>
<script>
    <?php echo wp_json_encode( $data_for_js ); ?>
</script>

There is also:

  • esc_html__ esc_attr__ etc ( escape translations too! )
  • esc_js - escape strings for javascript e.g. console.log(<?php echo esc_js($var); ?>);
  • esc_url_raw when redirecting, use this instead
  • esc_sql
  • esc_textarea
  • sanitize_text_field
  • Whitelisting values
  • type casting with (int) or absint
  • and others
0

yes, it is valid. as stands in reference https://developer.wordpress.org/reference/functions/esc_attr_e/ This function displays translated text that has been escaped for safe use in an attribute and what is safe for attribute is certainly safe in html text.

For simple strings (like 'Plugin Menu Name') this functions returns same output, but if you can, I recommend using appropriate function as already Tom J Nowell listed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.