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
You have at least two options:
Globalize the Variable
Wrap the Score Calculation
If you only ever need the score calculation inside the filter, pull the logic into the callback itself:
Better yet, you could wrap your score calculation in a function of its own, and then call that function inside your callback:
If you find you have problems referencing the
$_POST
object, you can also register your query variable and then useget_query_var()
internally to get data:With this in place,
$_POST['Q']
can be replaced withget_query_var('Q')
.Call the function anywhere in your script to get the score, it will only be calculated once.
Another way, using anonymous functions:
The following example sees the variable
$my_calculation
in the global scope, however from within our local function we need to declareglobal $my_calculation
in order to access the variable in the global scope.This is just one way to go about it and it appears to be neat. Would this work for you?