How to properly escape a translated string?

I’m having trouble understanding how to escape a translated string with WordPress…

The following piece of code is from the WordPress codex :

function wpdocs_kantbtrue_init()
{
    $args = array(
        'labels' => array(
            'name'                  => _x( 'Recipes', 'Post type general name', 'recipe' ),
            'singular_name'         => _x( 'Recipe', 'Post type singular name', 'recipe' ),
            'menu_name'             => _x( 'Recipes', 'Admin Menu text', 'recipe' ),
            'name_admin_bar'        => _x( 'Recipe', 'Add New on Toolbar', 'recipe' ),
            'add_new'               => __( 'Add New', 'recipe' ),
            'add_new_item'          => __( 'Add New recipe', 'recipe' ),
            'new_item'              => __( 'New recipe', 'recipe' ),
            'edit_item'             => __( 'Edit recipe', 'recipe' ),

            ... 
        )
    );

    register_post_type('Recipe', $args);
}
add_action('init', 'wpdocs_kantbtrue_init');

I think I read somewhere that everything should be escaped and I am pretty sure that the __() function does not escape anything, it just returns the translated text…

I have also seen this somewhere :

$wp_customize->add_setting('address', array(
    'default'           =>  esc_html__('Enter your Address in this field', 'themename'),
    'sanitize_callback' =>  'sanitize_text_field',
    'transport'         =>  'postMessage'
));

So what’s the safest way to do this ?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

WordPress has a baked in solution:

esc_html__( string $text, string $domain = 'default' )

You can use that to replace __() and __x() but the second one looks for contextual translations where you specify the context for the string being translated.

The codex for it is right here:
https://developer.wordpress.org/reference/functions/esc_html__/


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x