latest version

Escaping & Translations

In the theme, every output needs to be translatable and properly escaped due to security reasons. Introductory reading:

What needs to be escaped

  • All php variables following echo should be escaped

    echo $var;                                      // wrong
    echo esc_html( $var );                          // ok
    
  • All php functions following echo should be escaped

    echo home_url( '/' );                           // wrong
    echo esc_url( home_url( '/' ) );                // ok
    
  • All translations should be escaped

    echo __( 'Hello', 'ct_theme' );                 // wrong
    echo esc_html__( 'Hello', 'ct_theme' );         // ok
    
    _e( 'Hello', 'ct_theme' );                      // wrong
    esc_html_e( 'Hello', 'ct_theme' );              // ok
    
  • All attributes should be escaped

    <li id="accordion-section-<?php echo $this->id; ?>" class="<?php echo $classes ?>">                             // wrong
    <li id="accordion-section-<?php echo esc_attr( $this->id ); ?>" class="<?php echo esc_attr( $classes ); ?>">    // ok
    
  • Variables should not and can not be translated

    echo esc_html__( $var );                        // wrong, generates a notice
    echo esc_html__( $var, 'ct_theme' );            // wrong
    echo esc_html( $var );                          // ok
    

Variables containing HTML

When outputting a variable which contains HTML you can do one of the following:

  • Use wp_kses or wp_kses_post function to define allowed HTML tags
$var = 'Hello <b>world</b>';

echo $var;                                              // wrong
echo esc_html( $var );                                  // ok, but <b> tag is lost
echo wp_kses( $var, array( 'b' );                       // ok

Double check

Make sure you have everything escaped before publishing a theme. In order to double check, search the project for:

  • echo $
  • __( or better a regex: \W__\(
  • _e(
  • href=
  • src=
  • home_url(
  • permalink(