1

The following works but isn't up to snuff with PHP Code Sniffer WordPress coding standards

<?php esc_html_e( ADDRESS, 'wprig' ); ?>

Linter yells at me with:

[WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS".

The following, for aforementioned error, also don't work:

<?php esc_html_e( (string)ADDRESS, 'wprig' ); ?>
<?php esc_html_e( strval(ADDRESS), 'wprig' ); ?>
<?php esc_attr_e( ADDRESS, 'wprig' ); ?>

I know constants can be exploited so it is needed. Any way to make this work besides //phpcs:ignore, or is this not good practice and I should redo my use of constants?

3
  • 3
    Hey, nobody at VIP uses those standards and they're in the process of being deprecated, also don't use constants in translation APIs, see github.com/Automattic/VIP-Coding-Standards for better VIP coding standards. Additionally, if you're working on a VIP project you can raise a ticket
    – Tom J Nowell
    Commented Jun 29, 2018 at 22:59
  • My bad, double checked and I'm using WordPress standards. I've got the WordPress-VIP as default but project is using just WordPress. (And no, not working on a VIP project, I wish) Commented Jun 29, 2018 at 23:01
  • 4
    You should avoid the VIP standards that come bundled with WPCS, they're unmaintained and don't reflect the actual VIP standards that VIP uses
    – Tom J Nowell
    Commented Jun 29, 2018 at 23:05

3 Answers 3

11

You cannot use constants or anything other than actual strings with translation functions.

This is because the code that reads your code, and produces the translatable strings does not actually run your code, it is reading your code.

Here is a more detailed post on the topic:

http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/

But the short version is this:

This is wrong:

<?php esc_html_e( ADDRESS, 'wprig' ); ?>

Nothing will make that right except this:

<?php esc_html_e( 'Actual String here', 'wprig' ); ?>
1
  • "does not actually run your code, it is reading your code " Ahhh, that clears that up. Makes perfect sense. Thank you very much. Commented Jun 30, 2018 at 3:02
-1

I was having a hard time finding the proper solution if it wasn't a constant.

This works for a variable and the value attribute:

<input type="hidden" value="<?php echo esc_attr( $image_id ); ?>">
-1

According to the documentation of WordPress,

a variable and should not be part of the translation

Thus, you need to use printf instead of _e (echo). Thus the <?php esc_html_e( ADDRESS, 'wprig' ); ?> will be

esc_html(
    printf(
        __( '%s', 'wprig' ),
        ADDRESS // it can simply be a normal variable 
    )

);

Documentation from WordPress

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.