5

I need a little help getting my head around passing instance variable to a hook.

I am reading the CSS files I need in my template dynamically and storing them in a $settings object that I am keeping inside the scope of my plugin namespace.

So I want to do something like this:

add_action( 'wp_enqueue_scripts',function() {
    \mynamespace\ScriptQueuer::QueueCss($settings->GetCss());
} );

but obviously I need to pass the $settings->GetCss() return value into the scope somehow.

Do I make my $settings object global somehow? I am not sure how to do that and also not sure its the best approach. Is there anyway to achieve this or do I have to have all the CSS files hardcoded in a static function?

  • Have you tried function() use ( $settings ) {? – fuxia Apr 21 '15 at 14:31
  • That has worked, the code is now firing but it has thrown a load of errors elsewhere which I am going through now. Is it bad practice to queue scipts with anonymous function? I just read elsewhere this is not a good thing to do as you cannot remove the script or something. – Guerrilla Apr 21 '15 at 14:45
5

The best way to solve this is to simplify your code. Right now, ScriptQueuer::QueueCss() is just a static method, and it is getting its data too late.

You could use an immutable object instead and then just register one of its methods as callback.

Example:

class Enqueuer {

    private $stylesheets;

    public function __construct( ArrayObject $stylesheets ) {

        $this->stylesheets = $stylesheets;
    }

    public function enqueue() {

        foreach ( $this->stylesheets as $stylesheet )
            wp_enqueue_script(
                $stylesheet->handle(),
                $stylesheet->url(),
                $stylesheet->dependencies(),
                $stylesheet->version(),
                $stylesheet->in_footer()
            );
    }
}

add_action( 'wp_enqueue_scripts', [
    new Enqueuer( $settings->GetCss() ),
    'enqueue'
] );

No need to pass data to the enqueue method, no need for a closure, and the code is easy to read.

  • This is much better. Thanks, going to refactor along these lines. – Guerrilla Apr 21 '15 at 15:47
  • Hahaaa, loving the [] construct! Took me like a full minute to understand. – lkraav Apr 22 '15 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.