February 8, 2020

Essential WordPress Hooks Every Developer Should Know (with Practical Examples) – Part 3

One of the coolest features of WordPress is that almost every piece of text can be translated into different languages. If your website is in English, you might not need this, but not everyone runs an English-only website.

The gettext filter allows you to easily change text in different ways. Let’s look at an example:

Example: Fixing Grammar Mistakes from Developers

Imagine you found a great plugin, but the developer’s English is not very good, and there are many spelling mistakes in the text. Luckily, you can “retranslate” these strings using the gettext filter:

add_filter( 'gettext', 'gettext_example', 20, 3 );

function gettext_example( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'E-meil Adress' :
            $translated_text = __( 'Email Address', 'plugin_text_domain' );
            break;
    }
    return $translated_text;
}

Optimizing Title SlugsYour Attractive Heading

WordPress uses a function called sanitize_title() to automatically clean up titles. It replaces spaces with hyphens and saves the result as the post slug (URL-friendly title).
We can extend this behavior with the sanitize_title filter.

Example: Remove “the” from Title Slugs

If you don’t want the word “the” to appear in your post slugs, you can use this code:

add_filter( 'sanitize_title', 'sanitize_title_example' );

function sanitize_title_example( $title ) {
    $title = str_replace( '-the-', '-', $title );
    $title = preg_replace( '/^the-/', '', $title );
    return $title;
}

Excluding Shortcodes from TexturizationYour Attractive Heading

The wptexturize() function in WordPress automatically changes plain text characters (like quotes) into nicer versions.
Sometimes, you don’t want WordPress to change text inside shortcodes. You can do this using the no_texturize_shortcodes filter.

Example: Exclude a Shortcode from Texturization

Here’s how you exclude a shortcode:

add_filter( 'no_texturize_shortcodes', 'no_texturize_shortcodes_example' );

function no_texturize_shortcodes_example( $shortcodes ) {
    $shortcodes[] = 'myshortcode';
    return $shortcodes;
}

Filtering Comment Approval Status

WordPress has a system to check if a comment is spam or not before adding it to the moderation or approved list.
You can change how WordPress judges comments using the pre_comment_approve filter.

Example: Mark Comments with Long Author Names as Spam

In some countries, spam comments often use very long author names or URLs.
The code below marks such comments as spam automatically:

add_filter( 'pre_comment_approved', 'pre_comment_approved_example', 99, 2 );

function pre_comment_approved_example( $approved, $commentdata ) {
    return ( strlen( $commentdata['comment_author'] ) > 75 ) ? 'spam' : $approved;
}

Configuring Post by Email

Did you know you can post to WordPress by sending an email?
Although rarely used, WordPress supports this, and you can control it using the enable_post_by_email_configuration filter.

Example: Enable or Disable Post by Email

If you want to disable this feature (for example, for security reasons), just add:

add_filter( 'enable_post_by_email_configuration', '__return_false', 100 );

Filtering Page Titles

WordPress uses the wp_title() function to output the page title you see in the browser tab.
You can customize it with the wp_title filter.

Example: Customize the Page Title

add_filter( 'wp_title', 'wp_title_example', 10, 2 );

function wp_title_example( $title, $sep ) {
    global $paged, $page;

    if ( is_feed() )
        return $title;

    // Add the site name
    $title .= get_bloginfo( 'name' );

    // Add site description on home/front page
    $site_description = get_bloginfo( 'description', 'display' );
    if ( $site_description && ( is_home() || is_front_page() ) )
        $title = "$title $sep $site_description";

    // Add page number if necessary
    if ( $paged >= 2 || $page >= 2 )
        $title = sprintf( __( 'Page %s', 'tuts_filter_example' ), max( $paged, $page ) ) . " $sep $title";

    return $title;
}

Example source: tommcfarlin.com

Preprocessing Comments Before Saving

If you want to modify comment data (like name, email, URL, etc.) before saving it to the database, you can use the preprocess_comment filter.

Example: Convert Uppercase Comments to Lowercase

add_filter( 'preprocess_comment', 'preprocess_comment_example' );

function preprocess_comment_example( $commentdata ) {
    if( $commentdata['comment_content'] == strtoupper( $commentdata['comment_content'] ))
        $commentdata['comment_content'] = strtolower( $commentdata['comment_content'] );
    return $commentdata;
}

Redirect After Login

You can change where users are redirected after logging into WordPress using the login_redirect filter.

Example: Redirect Subscribers to the Homepage

add_filter( 'login_redirect', 'login_redirect_example', 10, 3 );

function login_redirect_example( $redirect_to, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if ( in_array( 'subscriber', $user->roles ) ) {
            return home_url();
        } else {
            return $redirect_to;
        }
    }
    return;
}

Adding a Settings Link for Your Plugin

When developing a WordPress plugin, you might want to add a “Settings” link right on the Plugins page.
You can do that using the plugin_action_links_ filter.

Example: Add a Settings Link

add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'plugin_action_links_example' );

function plugin_action_links_example( $links ) {
    $links[] = '<a href="' . get_admin_url( null, 'options-general.php?page=my_plugin_settings' ) . '">' . __( 'Settings' ) . '</a>';
    return $links;
}

Prefill the Post Editor

Sometimes, you might want to prefill the post editor with some default content or reminders for authors.
You can do this using the the_editor_content filter.

Example: Add Reminder Text in the Post Editor

add_filter( 'the_editor_content', 'the_editor_content_example' );

function the_editor_content_example( $content ) {
    if ( empty( $content ) ) {
        $template  = 'Hey! Don\'t forget to...' . "\n\n";
        $template .= '<ul><li>Come up with good tags for the post,</li><li>Set the publish time to 08:00 tomorrow morning,</li><li>Change the slug to a SEO-friendly slug,</li><li>And delete this text, hehe.</li></ul>' . "\n\n";
        $template .= 'Bye!';
        return $template;
    } else {
        return $content;
    }
}