Filterable text strings in WordPress

|

Note: Content might be outdated!

It is quite a common support case that WordPress users need to change a specific text string in a plugin or theme. Whilst customizing translated text hopefully will become a lot easier with language packs from WordPress 4.0 upwards, adjusting default strings in a theme or plugin can be quite a frustrating experience. Here’s an idea what theme and plugin authors can do to make UI customization easier.

The pain of customizing default text in a theme or plugin

When you need to change default text strings of a theme, let’s say to taylor a specific line of text for a client project, you may well feel tempted to hack original theme files. Which, of course, you shouldn’t. Never. Ever.

So you’re going to create a child theme, copy the entire template file you need to change text in and do it. Not a big deal as long as it’s one to two templates you’re duplicating.

However, when you regularly find yourself copying two-digit numbers of files from parent to child themes just in order to be able to change a couple of lines of text, you may wonder what other solutions there might be.

Solutions?

There are a couple. You can, for instance, apply the gettext() axe.

Yet, how nice would it be if the theme author would have thought of you and provided tools for you to easily solve the problem right where it occurs, addressing only the templates you need to modify, but without any duplication?

Example with _s starter theme

For the following example I’ve borrowed the footer.php file from the most popular _s starter theme by Automattic.

Even though _s is made for hacking and not for child themes, we’re going to assume we want to modify a text string in _s’s footer.php via functions.php of an imagined child theme. We then not only want to exchange, but also add custom text and keep it translatable through our child theme’s own text domain.

I’ve altered footer.php with a filterable array of $template_text (pretending it was already included in the original _s footer template).

The functions.php below then is meant to be part of my imagined child theme, obviously, and not of _s itself.

How would you do it?

Developers probably will argue the approach above will create a significant overhead in a theme or plugin for a relatively marginal use case. It might when used without thought, and implementation certainly could be improved either.

Nonetheless, here’s one idea to your kind notice, theme and plugin developers! Approval? Objections? Shoot away in the comments.