Category: WordPress

  • Escaping and Translating Text in WordPress

    WordPress core provides developers with a handful of functions to escape string content and enable translations into other languages.

    Translatable Strings

    Access the translated version of text used in plugins or themes with one of the following functions.

    <?php
    echo __( 'Hello', 'text-domain' );
    _e( 'Hello', 'text-domain' );
    echo _x( 'Hello', 'The welcome message', 'text-domain' );

    The first, __(), returns the text.

    The “e” in _e() stands for echo. This function outputs the text.

    The “x” in _x() stands for context and accepts an argument to explain to translators the context of the text.

    Escape for HTML

    Escapes strings so they are not parsed as HTML. Characters like < are converted to &lt;.

    <?php
    echo esc_html( 'Hello' );
    echo esc_html__( 'Hello', 'text-domain' );
    esc_html_e( 'Hello', 'text-domain' );
    echo esc_html_x( 'Hello', 'The welcome message', 'text-domain' );

    Example

    <p><?php esc_html_e( 'Hi there! >:)', 'my-plugin' ); ?></p>

    The above code will render the following HTML:

    <p>Hi there! &gt;:)</p>

    Escape for HTML attributes

    Escape strings used in HTML attributes like class="" so they do not break the HTML.

    <?php
    echo esc_attr( 'Value' );
    echo esc_attr__( 'Value', 'text-domain' );
    esc_attr_e( 'Value', 'text-domain' ); // Outputs the value.
    echo esc_attr_x( 'Value', 'The control value', 'text-domain' );

    Example

    <p><input type="text" value="<?php esc_attr_e( 'Something seems "off"', 'my-plugin' ); ?>" /></p>

    The above code will render the following HTML:

    <p><input type="text" value="Something seems &quot;off&quot;" /></p>

    Escape a URL

    Escape strings inside href="" or src="" attributes.

    <?php
    echo esc_url( 'https://coreysalzano.com/' );

    Escape for textareas

    Prevents the text content of a <textarea> from closing the element early.

    <?php
    echo esc_textarea( 'WordPress core provides developers with a handful of functions to escape string content and enable translations into other languages.' );
  • Akismet Alternatives

    Blocking spam on WordPress websites is heavy work. Akismet comes pre-installed on every site, but it’s not free for businesses or the only way to stop spam.

    1. OOPSpam https://www.oopspam.com/
    2. CleanTalk https://cleantalk.org/
    3. Stop Forum Spam https://www.stopforumspam.com/
    4. Project Honey Pot https://www.projecthoneypot.org/
    5. Zero Spam https://www.zerospam.org

    There are a ton of anti-spam WordPress plugins. The criteria for this list of alternatives is “offers an API.”

    Thanks to Austin and Kerch for inspiration and help creating this list.