Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a variable to an anonymous function in a wordpress filter

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;

}
like image 354
jhodgson4 Avatar asked Dec 11 '22 12:12

jhodgson4


1 Answers

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

like image 143
fuxia Avatar answered Feb 15 '23 11:02

fuxia