문제

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

다른 팁

The params you can provide to custom filters are defined by the filter and the way filters work in Wordpress. See http://codex.wordpress.org/Plugin_API/Filter_Reference for documentation about filters in Wordpress.

Also you're not the first attempting this so maybe this will help you (as I don't have a Wordpress install to test it with): http://wordpress.org/support/topic/change-the-title-dynamically

If you can't get it working I would suggest using the forum of the plugin you're using or contacting the developer directly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top