I find myself needing to pass custom data to a filter provided by a 3rd party plugin. All of the ways I've seen to do this are really complicated and hard to wrap my head around.
Take this example:
$score = 42; //Some crazy calculation I don't want to repeat.
function add_score_to_title($title) {
return 'Quiz Results (' . $score . '/') - ' . $title;
}
add_filter( 'aioseop_title_single', 'add_score_to_title');
How can I pass the $score
variable to add_score_to_title()
?
What I ended up doing was adding my variable onto the global $wp
object. So you end up with this:
global $wp;
$score = 42; //Some crazy calculation I don't want to repeat.
$wp->some_random_name_for_score = $score;
function add_score_to_title($title) {
global $wp;
$score = $wp->some_random_name_for_score;
return 'Quiz Results (' . $score . '/') - ' . $title;
}
add_filter( 'aioseop_title_single', 'add_score_to_title');
Dirty? Maybe. Simple? Yup! Any downsides to this technique? Please discuss.
UPDATE Here is the complete code in question -> http://pastebin.com/fkSXY04m
$score
is calculated by looping over an array of things and incrementing a variable. pastebin.com/fkSXY04m