Filtering WordPress Titles

stranger portrait - what?

As you may have seen here before VA passed a bill saying universities can’t have student email visible without written consent from the student. We had a legacy site that had student emails as part of the title structure for the posts.

We had stuff titled stuff like This is twwoodward@ecuniv.edu post or This is twwoodward@mymail.ecuniv.edu. We want to remove a chunk so it’s not an obvious email any longer.

The following function cleans up our two different email patterns so that the titles no longer include emails. It does this by tying a custom function to a WordPress filter.

The first thing we do is get the post type. In this case we just want a custom post type we named profile. $type = get_post_type( get_the_ID( ) ); should get us that variable.

Next, we’re defining the things we’d like to find in the title. $find = array(‘@mymail.vcu.edu’, ‘@vcu.edu’); – this is letting us look for multiple items and it could be many more than two.

Now our if loop only runs if the $type equals ‘profile’ otherwise it just passes the $title variable right back unharmed. If it is a profile custom post type, it uses PHP’s built in str_replace function to look for the things we defined in $find, replaces them with our second variable (” in this case which is just an empty string), and the third variable is $title which is the target of our find/replace pattern.

The final add_filter line says what is being filtered (the_title) and what filter/function is being run on it (the one we just wrote called suppress_email).

function suppress_email( $title, $id = null ) {
    $type = get_post_type( get_the_ID() );
    $find = array('@mymail.vcu.edu', '@vcu.edu');
    if ( $type === 'profile') {
        $title = str_replace($find,'',$title);
    }

    return $title;
}
add_filter( 'the_title', 'suppress_email', 10, 2 );

This is a tiny example and is no doubt simple for anyone who does this stuff regularly but I’m hoping that by breaking things down a bit more explicitly than I usually do it might help some other wandering souls who are early in the game. Have faith people. All this stuff makes more and more sense as you go on and then you can be completely confused by entirely new things.