March 1, 2020

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

Filter Search Queries

In a WordPress site, search functionality is fundamental. Using the posts_search filter hook, you can flexibly modify SQL queries.

Example: Include Password-Protected Posts in Search Results

Suppose you store client information in password-protected posts. To allow clients to search these posts using keywords (instead of manually browsing), you can use the following code:

add_filter( 'posts_search', 'posts_search_example' );

function posts_search_example( $search ) {
    global $wpdb;
    if ( !is_user_logged_in() ) {
        $pattern = " AND ({$wpdb->prefix}posts.post_password = '')";
        $search = str_replace( $pattern, '', $search );
    }
    return $search;
}

Set Image Compression Quality on Upload

By default, WordPress compresses resized images during upload. You can control the compression quality using the wp_editor_set_quality filter.

Example: Disable WordPress Image Compression

If your users (such as designers) are sensitive to minor image distortions caused by PHP compression, you can disable compression with the following code:

add_filter( 'wp_editor_set_quality', 'wp_editor_set_quality_example' );

function wp_editor_set_quality_example( $quality ) {
    return 100;
}

Filter Text Widgets

WordPress widgets have their own filter hooks. For the Text widget, the filter is widget_text.

Example: Enable Shortcodes in Text Widgets

By default, WordPress does not allow shortcodes in Text widgets. You can enable it with this code:

add_filter( 'widget_text', 'do_shortcode' );

Filter Content in RSS Feeds

Just as you can filter post content with the_content, you can filter feed content using the_content_feed.

Example: Insert Featured Images into Feeds

add_filter( 'the_content_feed', 'the_content_feed_example' );

function the_content_feed_example( $content ) {
    $featured_image = get_the_post_thumbnail( get_the_ID(), 'thumbnail', array( 'style' => 'float:left;margin-right:.75em;' ) );
    $content = get_the_excerpt() . ' <a href="'. get_permalink() .'">' . __( 'Read More' ) . '</a>';
    if ( '' !== $featured_image ) {
        $content = '<div>' . $featured_image . $content . '<br style="clear:both;" /></div>';
    }
    return $content;
}

Customize Visual Editor Buttons

The WordPress editor (TinyMCE) can be customized using the mce_buttons filter.

Example: Remove Unwanted Buttons from the Visual Editor

add_filter( 'mce_buttons', 'mce_buttons_example' );

function mce_buttons_example( $buttons ) {
    $remove_array = array( 'strikethrough', 'blockquote', 'hr', 'alignleft', 'aligncenter', 'alignright', 'wp_more', 'wp_adv' );
    foreach ( $remove_array as $remove ) {
        if ( ( $key = array_search( $remove, $buttons ) ) !== false ) {
            unset( $buttons[ $key ] );
        }
    }
    return $buttons;
}

Exclude Certain Categories from Lists

Sometimes you want to exclude specific categories from the category list. Use the list_terms_exclusions filter.

Example: Exclude Plugin-Specific Categories

add_filter( 'list_terms_exclusions', 'list_terms_exclusions_example', 10, 2 );

function list_terms_exclusions_example( $exclusions, $args ) {
    $exclude = "42,132"; // IDs of categories to exclude
    $exterms = wp_parse_id_list( $exclude );
    foreach ( $exterms as $exterm ) {
        if ( empty( $exclusions ) ) {
            $exclusions  = ' AND ( t.term_id <> ' . intval( $exterm ) . ' ';
        } else {
            $exclusions .= ' AND t.term_id <> ' . intval( $exterm ) . ' ';
        }
    }
    if ( !empty( $exclusions ) ) {
        $exclusions .= ')';
    }
    return $exclusions;
}

Add Custom Image Sizes to Media Insert Dropdown

You may want to let authors choose a custom image size when inserting images into posts.

Example: Add a Custom Size Called “Golden Ratio Thumbnail”

add_filter( 'image_size_names_choose', 'image_size_names_choose_example' );

function image_size_names_choose_example( $sizes ) {
    return array_merge( $sizes, array(
        'golden-ratio-thumb' => __( 'Golden Ratio Thumbnail' )
    ) );
}

Customize the “More” Text in Excerpts

WordPress by default uses […] to indicate truncated excerpts. You can customize it using the excerpt_more filter.

Example: Add a “Read More” Link

add_filter( 'excerpt_more', 'excerpt_more_example' );

function excerpt_more_example( $text ) {
    global $post;
    return '... <a class="read-more-link" href="' . get_permalink( $post->ID ) . '">Read more</a>';
}

Manage Columns in the Posts Admin List

In the WordPress dashboard, you can customize the columns shown in the “All Posts” view using manage_posts_columns.

Example: Remove the Author Column

add_filter( 'manage_posts_columns', 'manage_posts_columns_example' );

function manage_posts_columns_example( $columns ) {
    unset( $columns['author'] );
    return $columns;
}

Edit User Contact Information Fields

You can add or remove fields from the user profile form using user_contactmethods.

Example: Add New Social Media Fields and Remove Outdated Ones

add_filter( 'user_contactmethods', 'user_contactmethods_example' );

function user_contactmethods_example( $contactmethods ) {
    unset( $contactmethods['yim'] );
    unset( $contactmethods['aim'] );
    unset( $contactmethods['jabber'] );

    $contactmethods['twitter'] = 'Twitter Username';
    $contactmethods['facebook'] = 'Facebook Profile URL';
    $contactmethods['linkedin'] = 'LinkedIn Profile URL';

    return $contactmethods;
}