Wordpress - Should `get_template_directory_uri()` be escaped?

In that function we find a hook:

return apply_filters( 
    'template_directory_uri', 
    $template_dir_uri, 
    $template, 
    $theme_root_uri
);

So, yes, the URI can be changed by plugins, and you should escape its returned value.

The same principle applies to all WordPress URI functions, like get_home_url(), get_site_url() and so on. Keep in mind that there are not only good plugin developers out there. Some make mistakes, maybe just very small ones that happen only in some circumstances.

In case of wp_enqueue_style(), WordPress does escape the URL by default. But that is a wrapper for the global WP_Styles instance, and this in turn can be replaced easily – even with a less safe version. That's not very likely, but you should be aware of this possibility.

Unfortunately, WP itself doesn't follow the better safe than sorry directive. It doesn't even escape translations. My advice is not to look at the core themes for best practices. Always look at the source of the data and see if it can be compromised.


Will try to make swissspidy's comment into an answer. Short version - it depends.

Escaping should not be applied randomly as double escaping might produce a url (or any kind of content) which do not match the intended url. Escaping should be applied only before output. Therefor the context is more important then the specific function that calculates the URL.

In your example, the first snippet just enqueues the URL and do not output it. The responsibility for escaping is delegated further into the wordpress stack to the code that actually output it, and that is the reason it is not escaped.

The second snippet does the output and that is why the url is being escaped.

So how do you know when you should not escape? Hopefully somewhere in the future the documentation of wordpress APIs will include that information, but for now either follow the full code path until the actual output, or test your theme under "funny" urls