should I escape a literal url added in functions.php

I added a snippet to my functions.php file to add credit card icons in the woocommerce checkout page. The icons are in my media library so I added the url of the image. This is not an input and it will not be changed, should I escape it anyway?

the code:

add_action ('woocommerce_review_order_before_submit', 'my_custom_woocommerce_icons');

function my_custom_woocommerce_icons() {

    $icons  = 'div class=checkout-icons-container
        
    img src=https://mywebsite.com/wp-content/uploads/2022/01/visa02.png alt=visa /
img src=https://mywebsite.com/wp-content/uploads/2022/01/mastercard.png alt=mastercard/
    /div';

     echo $icons;
}

Topic escaping security Wordpress

Category Web


No, you don't have to escape values that cannot be changed by someone else.

You should escape output that might be changed by some other source, for example if there is a filter running on the values.

Let's say you are using wp_upload_dir() to find the upload directory – and you absolutely should, because the location of that directory can be customized! — then there are various filters in play, so you should escape the final URLs.

Or if you insert your own filter option, so you can change the URL per plugin or child theme – again, you need escaping.

Example:

$upload_dir = wp_upload_dir();
$upload_url = $upload_dir['baseurl'];
$payment_icons = [
    'visa'       => $upload_url . '/2022/01/visa02.png',
    'mastercard' => $upload_url . '/2022/01/mastercard.png',
];
$payment_icons = apply_filters( 'theme_payment_icons', $payment_icons );

foreach( $payment_icons as $alt => $url ) {
    printf(
        '<img src="%1$s" alt="%2$s">',
        esc_url( $url ), // we escape as late as possible!
        esc_attr( $alt )    
    );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.