0

maybe it's not such a big deal as I think it is, but I want to escape href attribute with some text. Which one of these examples is the "correct" one - and does it actually matter?

<?php printf( esc_html__( '%1$s and %2$s.', 'theme_name' ), 'One', '<a href="http://example.com/">Two</a>' ); ?>
<?php printf( __('One and <a href="%1$s" class="class">%2$s</a>.', 'theme_name'), esc_url( __( 'http://example.com/' ) ), esc_html__( 'Two' ) ); ?>

I'm asking because the second one is using esc_url for URL, which to me, seems more secure than the first one.

thanks

  • These code samples do not yield the same output. Could you correct the code in your post, or are they not intended to yield the same output? – engelen Mar 29 '16 at 14:30
  • Ahh, sorry, didn't notice I made a mistake. Now it's working. – Kailo Mar 29 '16 at 14:34
0

The use of escaping data before outputting it to the browser ensures that no malicious (external) content (over which you have no control) can be outputted to the browser, and that no errors occur in HTML tags. Additionally, translated strings can be escape to make sure their translations have no unescaped special characters.

In your case, the second option you present is better than the first. Instead of escaping the entire HTML and leaving in the A-tag, you can assume that you yourself have correctly formatted the A-tag and escape the contents. However, in general, you don't have to apply __() to a URL, as it doesn't really have a translation (expect if you've hardcoded a link to a multilingual website, but that's very unlikely ;-)). The best approach would be:

printf( __( 'One and <a href="%1$s">%2$s</a>.', 'theme_name'), esc_url( 'http://example.com/' ), __( 'Two' ) );

Which ensures that all tag content is escaped properly, that all text can be translated, all the while ensuring flexibility in the two parts of the string. However, it is still a bit case-dependant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.