Replace an array of strings in content for Wordpress
-
22-09-2019 - |
Question
I'm working on a music blog that provides review scores ranging from 0.0 - 10. Since the authors already developed their system of typing in the score in the content, I'm trying figure out a way to emphasis them better.
Example:
"Score: 6.4"
returns something like
<div class="score">6.4</div>
Is there way to do this in an array to put every score possibility down within function.php or on the single.php page. Whatever is cleaner.
Solution
You can do a regular expression search/replace for the content. Then you can hook it into Wordpress by creating a plugin and using the wp add_filter function.
function expand_scores($content) {
return preg_replace('/(score):\s*([\d.]+)/ims', '<div class="score">$1: $2</div>', $content);
}
add_filter('the_content', 'expand_scores');
Both the expand_scores
and the add_filter
call go into your plugin file. The the_content hook applies the expand_scores function to all post data retrieved from the database before printing.