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

Inside functions.php:

add_action('init','my_action');

function my_action() {
    if($dontknow) {
        $passme = "yes";
    } else {
        $passme = "no";
    }
}

Inside index.php of the current theme:

echo $passme;

Is there a global to use for this purpose? Shall I use add_option (this is not a good idea for each request I guess)? Shall I use a custom global variable?

Is there a better / usual / standard way to do this?

4 Answers
4

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