Sometimes you may need to “filter” the value of the_title(). This can be done with the_title filter. Below are a few examples on how it can be used:
The WordPress Way
<?php
function custom_title_filter($title) {
// prepend "foo" to title string
$title = "foo" . $title;
// return updated title string
return $title;
}
add_filter('the_title', 'custom_title_filter');
The OOP Way
<?php
class Custom_Filters {
function __construct() {
add_filter('the_title', [$this, 'custom_title_filter']);
}
function custom_title_filter($title) {
// prepend "foo" to title string
$title = "foo" . $title;
// return updated title string
return $title;
}
}
new Custom_Filters();
The Anonymous Way
<?php
add_filter('the_title', function($title) {
// prepend "foo" to title string
$title = "foo" . $title;
// return updated title string
return $title;
});
All three of the above options do the same thing, there’ just implemented with different styles. If you are not sure which style to go with I recommend using option one: The WordPress Way. When you get into plugin development you will find many developers opt for the OOP Way.