Escaping built-in WP function return strings

Should one filter the output of builtin WP functions such as get_permalink() and well-known WP plugins such as ACF (Advanced Custom Fields) such as get_field()?

For instance get_permalink() calls home_url() which calls get_home_url(), none of which do any filtering of the data. In a similar fashion work the_content(), the_title() and the rest of the familiar Loop-related functions.

Therefore, is the following sufficient? (no esc_attr() for WP and ACF functions)

<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
    <a href="https://wordpress.stackexchange.com/questions/215822/<?=get_the_permalink()?>">
        <img src="<?=get_field('homepage_thumbnail')['sizes']['thumbnail']?>" />
    </a>
<?php endwhile; ?>

Or should I be more careful with the data coming from the plugin? (notice esc_attr() added to ACF image source, third line)

<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
    <a href="https://wordpress.stackexchange.com/questions/215822/<?=get_the_permalink()?>">
        <img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
    </a>
<?php endwhile; ?>

Or should I be super careful even with the stock WP functions? (notice esc_attr() added to WP anchor href, second line)

<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
    <a href="https://wordpress.stackexchange.com/questions/215822/<?=esc_attr(get_the_permalink())?>">
        <img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
    </a>
<?php endwhile; ?>

2 Answers
2

Escaping is used to produce valid HTML or other formats, and it depends on context.

Escaping a url in something like <a href="https://wordpress.stackexchange.com/questions/215822/<?php echo $url?>".... is needed in order to replace any “&” characters with & (although browsers will most likely fix it for you if you don’t do it).

Escaping a url in an input element like <input value="https://wordpress.stackexchange.com/questions/215822/<?php echo $url?>"...do not require replacement of “&” but do require replacement of any quote character.

So in general, since escaping is context sensitive you can assume that wordpress API will not escape it for you. What plugins do, is up to the plugin itself.

Leave a Comment