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.

Leave a Comment