Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

e.g.

// 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?

share|improve this question
add comment

3 Answers

up vote 3 down vote accepted

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

share|improve this answer
    
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
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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