1

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 ?

0

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__/

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.