When I am putting a WordPress value inside the attribute tag, for example, the following method does not need esc_attr


// JS code
alert('<?php echo get_bloginfo('name');?>');

the following method does need esc_attr

// JS code
alert('<?php echo esc_attr($post->post_title);?>');

What is the convention used?


You can look at the Codex.

Encodes < > & " ' (less than, greater than, ampersand, double quote, single quote). Will never double encode entities.

Given that, arguably, both of those strings need sanitization. Imagine a site name like >> "My" Website's Great Title <<"

Also, since you are using this in Javascript, you should probably be using esc_js instead.

The convention is, "understand how markup works, and how malicious hackers work, and act accordingly." That is how you know how to use these functions. Also, Trust No One.

See also this article from our member Stephen Harris: Data Sanitization and Validation With WordPress

  • Actually my finding is get_bloginfo('name'); does not need to be escaped, when I set my blog name as "My" Website's Great Title <<", and print it out via echo get_bloginfo('name') , it is already escaped, i.e. My&quot; Website&#039;s Great Title &lt;&lt;. – Howard Dec 12 '12 at 10:50
  • You can reference this: themes.svn.wordpress.org/twentyeleven/1.5/header.php, the default theme also print the blogname directly, e.g. bloginfo( 'name' ); – Howard Dec 12 '12 at 10:57
  • I wouldn't depend on the theme for this. – s_ha_dum Dec 12 '12 at 14:48

You use esc_attr() when you are outputting something intended to be in an HTML attribute.

In your case, you should be using esc_js(), or possibly json_encode() instead.


If your post title has single quote in it. Output of your code would be

alert('It's bad');

that is, breaking your JavaScript code and you will get "Unexpected identifier". When you use esc_attr, output would be

alert('It&#039;s bad');

Post title will be encoded so it works within the strings.

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.