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.

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

Solutions Collecting From Web of "When do I need to use esc_attr when using WordPress internal functions"

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

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.