Reputation: 2783
So I've got a class on which I've added different methods to customize my Wordpress theme. One of the methods is called limitExcerptToWords
, and what it does is limiting the length of the excerpt returned by WP.
The way you do this in WP is by adding a function to a hook, the function can be expressed as a string (name of the function), or like in my case, as an anonymous function. The value returned by this function will be the length of the excerpt.
My code looks like this:
class XX {
/* ... */
function limitExcerptToWords($numWords) {
add_filter( 'excerpt_length', function (){
return $numwords;
});
}
/* ... */
}
Then I would like to invoque that method like: $OBJ->limitExcerptToWords(10);
I'm much more knowledgable in JS, where this code would work jsut fine, but PHP has a different way of dealing with scopes, and as a result the code inside my anonymous function doesn't have $numWords
in scope.
I've been reading through the PHP docs but I can't gind a way of getting this to work in an elegant way.
Can you help? :3
Thanks!
Upvotes: 0
Views: 50
Reputation: 15625
If you want to use it inside the anom function you need to pass it with use
class XX {
/* ... */
function limitExcerptToWords($numWords) {
add_filter( 'excerpt_length', function () use($numWords) {
return $numwords;
});
}
/* ... */
}
Upvotes: 2