0

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!

1

1 Answer 1

2

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;
        });
   }
   /* ... */
}
Sign up to request clarification or add additional context in comments.

1 Comment

As if by magic!! Somehow I missed this when I first read the anonymous functions manual, found it now! (php.net/manual/en/functions.anonymous.php#example-197) Thanks a lot boss!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.