When do I need to use esc_attr when using WordPress internal functions

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

e.g.

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

Related posts

Leave a Reply

3 comments

  1. 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

  2. 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.

  3. 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's bad’);

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