Replace Words in Content on Display
Swaps words or phrases in post titles, content and excerpts when pages are shown, without editing the posts. Useful after a rebrand or a product rename.
Opens WPIDE on
Code
// Text to find => replacement.
$wpide_replacements = array(
'Old Brand Name' => 'New Brand Name',
'old-product' => 'new-product',
);
$wpide_replace_text = function ( $text ) use ( $wpide_replacements ) {
if ( ! is_string( $text ) || '' === $text || is_admin() ) {
return $text;
}
foreach ( $wpide_replacements as $find => $replace ) {
$result = preg_replace( '/' . preg_quote( $find, '/' ) . '(?![^<]*>)/u', str_replace( array( '\\', '$' ), array( '\\\\', '\\$' ), $replace ), $text );
$text = null === $result ? $text : $result;
}
return $text;
};
add_filter( 'the_title', $wpide_replace_text );
add_filter( 'the_content', $wpide_replace_text, 30 );
add_filter( 'the_excerpt', $wpide_replace_text );
Notes
Replacements are case-sensitive and skip HTML tags and attributes. The text saved in the database is not changed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.