When I am putting a WordPress value inside the attribute tag, for example, the following method does not need
// JS code alert('<?php echo get_bloginfo('name');?>');
the following method does need
// 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 <<"
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
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
If your post title has single quote in it. Output of your code would be
Post title will be encoded so it works within the strings.