as a matter of performance for the entire system, how to do it correctly, if there is a way, to make the code of my plugin read or interpreted only when the user will login, as it is only and exclusively to work when the user is logged in.

In this way, I decrease the load on the site, not having to run or read everything every request on the site.

I was thinking of doing something similar to that, but I still haven’t found a more viable way

$pluginPath="myPlugin/myPlugin.php";
if (is_plugin_active($pluginPath) && stripos($_SERVER['SCRIPT_NAME'], 'wp-admin') == true) {
...
}

3 Answers
3

When I create custom plugins I tend to add a single init function, which includes other plugin files, attached functions from these files to actions and hooks, etc. This way I have centralized place where the plugin is bootstrapped. This init function is then hooked to the plugins_loaded action in case I need to do some dependecy checking – i.e. some other plugin needs to be installed and active too.

// your-main-plugin-file.php
add_action('plugins_loaded', 'my_plugin_init');
function my_plugin_init() {
    // check dependencies
    // include files
    // hook plugin function to actions and filters
    // etc...
}

But the plugins_loaded action fires too early, if you also need to check for a logged in user. In that case a good action to hook your main init function to would be init as the user is authenticated by the time it is fired.

add_action('init', 'my_plugin_init_logged_in_users');
function my_plugin_init_logged_in_users() {
    if ( is_user_logged_in() ) {
        my_plugin_init();
    }
}

You can find more information about the different WP actions, their order and what data is available to them when they fire, in the Action reference.

Leave a Reply

Your email address will not be published. Required fields are marked *