Mangling strings for fun and profit

As a WordPress lead developer, every time I see someone recommending editing a core WordPress file, a little bit of me dies.

You should always avoid editing the core files and put your modifications into a plugin so as to ensure you have a smooth upgrade experience to a future WordPress version.

Therefore inspired by the following forum post here is how to change one of the translatable strings in WordPress without hacking a core file using the filters available in the translation functions:

<?php
/*
 Plugin Name: PJW Translation Mangler
 Plugin URI: http://blog.ftwr.co.uk/#
 Description: Example of how to mangle translated strings.
 Author: Peter Westwood
 Version: 0.01
 Author URI: http://blog.ftwr.co.uk/
 */

class PJW_Translation_Mangler {
 /**
 * Filter the translation string before it is displayed.
 *
 * @param $translation The current translation
 * @param $text The text being translated
 * @param $context The context for the translation
 * @param $domain The domain for the translation
 * @return string The translated / filtered text.
 */
 function filter_gettext($translation, $text, $domain) {
  $translations = &get_translations_for_domain( $domain );
  if ( $text == 'View all posts filed under %s' ) {
   return $translations->translate( 'See all articles filed under %s' );
  }
  return $translation;
 }
}
add_filter('gettext', array('PJW_Translation_Mangler', 'filter_gettext'), 10, 4);
?>

The filter used in this example gettext is one of a set of filters in the translation functions in wp-includes/l10n.php which also include gettext_with_context, ngettext, and ngettext_with_context.



d
go to dashboard
l
go to login
h
show/hide help
e
edit post/page
r
comment on post/page
m
go to moderate comments
esc
cancel