Passing a variable to an anonymous function in a wordpress filter

I am trying to override a plugin that creates SEO headers in wordpress. The filter does the job, but I need to create headers dynamically. So I create a header and then pass it to an anonymous function. I could have another function that creates headers, it will definitely be cleaner ...

It works

function seo_function(){ add_filter('wpseo_title', function(){ return 'test seo title'; }); } 

Is not

 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 the variable, I will have to duplicate the code to create a header.

Seo_function () {

 //create title above $title="test seo title"; add_filter('wpseo_title', 'seo_title'); } function seo_title(){ $title="test"; return $title; } 
+3
source share
2 answers

You pass variables to the closing area with the use keyword:

 $new_title = "test seo title"; add_filter( 'wpseo_title', function( $arg ) use ( $new_title ) { return $new_title; }); 

The function argument ($ arg) will be sent by calling apply_filters (), for example, by another plugin, not your code.

See also: Passing a parameter for filtering and actions

+11
source

The options you can provide for custom filters are determined by the filter and how filters work in Wordpress. See http://codex.wordpress.org/Plugin_API/Filter_Reference for documentation on filters in Wordpress.

Also, this is not the first time you are trying to do this, perhaps it will help you (since I do not have a Wordpress installation to test it): http://wordpress.org/support/topic/change-the-title-dynamically

If you cannot get it to work, I would suggest using the plugin forum you are using or contacting the developer directly.

0
source

Source: https://habr.com/ru/post/1493913/


All Articles