0

I am going through some example code from the codex for creating a widget (https://codex.wordpress.org/Widgets_API) . Below is the code for creating a label and input field for an admin widget form :

    <p>
    <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label> 
    <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
    </p>

I understand esc_attr() will escape html and make it proper for it to be used as an HTML attribute value . However , what I fail to understand is why would you use esc_attr() in the above cases when everything is hard coded ? I would think esc_attr would be used for user entered data .

For eg in the below code why is the label value being escaped even though a fixed string of ‘Title’ is being passed to it ? or the value for ‘for’ being escaped when we are passing a fixed string $this->get_field_id( ‘title’ ) to it ?

<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label>
  • 2
    Because esc_attr_e() displays translated text and the translator(s) could have used special characters there that need to or must be escaped. – Sally CJ Sep 7 at 10:39
0

All text entered into the database is, in essence, "user entered". If the site gets hacked a hacker could change every instance of the field "title" to contain javascript, for example. If you just echo out the field then you're writing the javascript to the page and thus injecting the code into the page.

Therefore, you should consider everything that comes from the database to be potentially hackable and use the appropriate esc_ function before writing it out.

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.