1

I'm setting up a child theme in WordPress and I can't make add_action to be fired within functions.php.

Functions.php is called and I can run code from within. Any idea on what I'm doing wrong?

$debug_msg = "Hi there!";

function test_function() {
    error_log($debug_msg, 0);

}
add_action('init', 'test_function', 20);
  • 1
    This code won't work, because you have your variable $debug_msg defined outside the function where it is called. Ohterwise it looks fine. – cjbj Jun 30 '16 at 9:38
  • Oh, you may also want to use wp_enqueue_scripts as a hook for enqueueing styles rather than init. – cjbj Jun 30 '16 at 10:40
2

If you want to use a variable from a another context in a function, create a class:

class CustomLog
{
    private $debug_msg = "";

    public function __construct( $msg )
    {
        $this->debug_msg = $msg;
    }

    public function log()
    {
        error_log( $this->debug_msg, 0 );
    }
}

add_action( 'init', [ new CustomLog( "Hi there!" ), 'log' ], 20 );

Now you can reuse the class multiple times for different messages and hooks.

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.