What is a good way to pass a variable from add_action to a Theme?

Use an object to keep the value of the variable and a custom action to print it out.

In your theme’s functions.php, create a class, or better: move the class to a separate file.

class PassCheck
{
    private $passed = 'no';

    public function check()
    {
        if ( is_user_logged_in() )
            $this->passed = 'yes';
    }

    public function print_pass()
    {
        echo $this->passed;
    }
}

Then register the callbacks:

$passcheck = new PassCheck;
add_action( 'init',       [ $passcheck, 'check' ] );
add_action( 'print_pass', [ $passcheck, 'print_pass' ] );

And in your template just call the proper action:

do_action( 'print_pass' );

This way, the template has no static dependency on the class: if you ever decide to remove the class or to register a completely different callback for that action, the theme will not break.

You can also move the check() callback to another action (like wp_loaded) or separate it out into another class later.

As a rule of thumb: templates (views) should be decoupled from business logic as much as possible. They shouldn’t know class or function names. This isn’t completely possible in WordPress’ architecture, but still a good regulative idea.

Leave a Comment