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>
esc_attr_e()
displays translated text and the translator(s) could have used special characters there that need to or must be escaped.