Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
Have you tried function() use ( $settings ) {? –  toscho yesterday
    
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 yesterday

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
This is much better. Thanks, going to refactor along these lines. –  Guerrilla yesterday
    
Hahaaa, loving the [] construct! Took me like a full minute to understand. –  lkraav 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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