0

I am trying to use php esc_html_e with a inside and must be missing something since I cant get it to work. My code is simple and is:

<p><?php esc_html_e('You are not logged in. <a href="/my-account/">Log in</a> or create an account to see questions and answers about this rental', 'dc-woocommerce-multi-vendor'); ?></p>

The above results in an output of You are not logged in. <a href="/my-account/">Log in</a> or create an account to see questions and answers about this rental on the page. What is it I am missing here?

1 Answer 1

2

The point of esc_html is to ensure that the end result is plaintext, no HTML tags or scripts etc, just plaintext. The __ part passes it through the localisation API, and the e indicates it will echo on its own. So what you are seeing is expected and normal.

Instead, you will need to make use of sprintf, you will need to eliminate the _e part and echo yourself, and you'll need to use a placeholder for the link.

something similar to this:

<p>
<?php
echo sprintf(
    esc_html__( 'Apples can be red or green %s', 'textdomain' ),
    '<a href="/apples">' . esc_html__( 'click here to learn about apples', 'textdomain' ) . '</a>'
);
?>
</p>

Remember, HTML tags inside localised strings are not good, they're a sign you've made a mistake or missed something. Avoid them and use placeholders or split them up into shorter strings.

They can also indicate problems with copy/grammar/SEO/accessibility. In this case, the highlighting of just the word log in suggests poor accessibility for those using screen readers or automated bots such as search engine crawlers. Here, the link says "log in" but the links text does not contain any context for why you might want to do that, or where the link leads, e.g. it's not clear that it leads to the my account page or that you can register via that page.

2
  • Thank you for that. I had incorrectly read you could do html. Quick not the above code is invalid as its missing a . . Here is correct for anyone in the future. Thanks @TomjNowell echo sprintf( esc_html__( 'Apples can be read or green %s ', 'textdomain' ) . '<a href="/apples">' . esc_html__( 'click here to learn about apples', 'textdomain' ) . '</a>' );
    – Bill
    Commented Dec 29, 2021 at 0:50
  • 1
    @Bill that is incorrect, you've misunderstoood the usage of sprintf, defeating the point of it, the %s is supposed to be replaced with the second argument passed to sprintf but you've removed it and appended it to the end. I've added the missing comma
    – Tom J Nowell
    Commented Dec 29, 2021 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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