I am trying to override a plugin that creates SEO titles in wordpress. The filter does the job but I need to dynamically create the titles. So I create the title then pass it to an anonymous function. I could have another function that creates the titles put this will definitely be cleaner...
This works
function seo_function(){
add_filter('wpseo_title', function(){
return 'test seo title';
});
}
This doesn't
function seo_function(){
//create title above
$title="test seo title";
add_filter('wpseo_title', function($title){
return $title;
});
}
Thanks for any help
Joe
Without using an anonymous function example - this works, but I still can't pass a variable, I'd have to duplicate code to create the title.
function seo_function(){
//create title above
$title="test seo title";
add_filter('wpseo_title', 'seo_title');
}
function seo_title(){
$title="test";
return $title;
}
You pass variables into the closure scope with the use
keyword:
$new_title = "test seo title";
add_filter( 'wpseo_title', function( $arg ) use ( $new_title ) {
return $new_title;
});
The argument in function($arg) will be sent by the apply_filters() call, eg the other plugin, not by your code.
See also: Passing a parameter to filter and action functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With