My plugin runs on every single WordPress page, but I want it to run only on activation

Question

My plugin is running on every single WordPress page, and I can’t find a WordPress hook so that the script will only run when the plugin is activated. I only want part of the script to run when the plugin is activated, but not when I navigate to other WordPress pages. Apologies if it’s a simple/basic solution I’m quite new to this.

I’ve tried register_activation_hook(FILE, ‘do_my_function’ ) but that gets me a “the plugin generated 1500 characters of unexpected output during activation. If you notice headers already sent messages…” error. If I try to debug this, all I get is "Fatal Error:" and a whole lotta blank space even though I’m not even outputting anything.

Can anyone help? Thanks in advance:)

Here’s the code:

class plugin
{
    function __construct()
    {
    }
    
    public static function activate()
    {   
        flush_rewrite_rules();
        //(new self) -> do_my_function(); //if I use this line instead of add_action it causes the "plugin generated 1500 characters of unexpected output" error
    }
    
    function do_my_function(){}

    function deactivate()
    {
        flush_rewrite_rules();
    }
}
if (class_exists('plugin'))
{
    $plugin = new plugin();
}
register_activation_hook( __FILE__, array($plugin, 'activate'));    
register_deactivation_hook( __FILE__, array($plugin, 'deactivate'));

add_action('admin_init', array($plugin, 'plugin_activated'), 10, 0); //causes plugin to run on every wordpress page load
0
wp_newbie 2 months 0 Answers 12 views 0

Leave an answer