Search code examples
phpwordpresswordpress-plugin-creation

How to inspect variables inside "register_activation_hook" in WordPress


I'm new to WordPress/PHP and I'm trying to create a WP plugin. I want to be able to inspect some code inside the register_activation_hook. This is the code that's being executed inside the register_activation_hook:

        $data_store = \WC_Data_Store::load('webhook');
        $all_hooks = $data_store->search_webhooks(
            array(
                'limit' => 10,
            )
        );
        $_items = array_map('wc_get_webhook', $all_hooks->webhooks);
        foreach ($_items as $webhook) {
            $name = $webhook->get_name();
            echo $name; // trying to inspect the name here
            if ($name === "Test Hook") {
                $webhook->set_status('active');
                $webhook->save();
            }
        }

When I install and then activate the plugin, I don't get any output anywhere, even if I use alert instead of echo. I saw some people saying that you shouldn't output anything inside the register_activation_hook. If that's the case, how can we inspect the values inside this hook?

I tried using a debugging plugin called Query Monitor, but it's also not capturing anything.


Solution

  • You can't pass output to the register_activation_hooksince it will return a Headers already sent error, you should catch the values you need with a transient and pass it to the admin_notices action, similar to this:

    register_activation_hook( __FILE__, 'initiate_webhooks' );
    function initiate_webhooks(){
      $data_store = \WC_Data_Store::load( 'webhook' );
            $all_hooks = $data_store->search_webhooks(
                array(
                    'limit' => 10,
                )
            );
            $_items = array_map( 'wc_get_webhook', $all_hooks->webhooks );
    
            set_transient( 'active_webhooks', wp_json_encode( $_items ) , 60 );
            foreach ( $_items as $webhook ) {
                $name = $webhook->get_name();
            
                if ( $name === "Test Hook" ) {
                    $webhook->set_status( 'active' );
                    $webhook->save();
                }
            }
    }
    
    add_action( 'admin_notices', function() {
        $webhooks = get_transient( 'active_webhooks' );
        if ( false !==  $webhooks ) {
    ?>
    <div class="notice notice-success is-dismissible">
    <?php
            $webhooks = json_decode( $webhooks );
            foreach( $webhooks as $webhook ) {
                echo $webhook;
            }
        ?>
     </div>
    <?php
        }
    });
    
    
    
    

    Don't forget to delete the transient. https://developer.wordpress.org/apis/transients/