Why does wpmu_new_user not fire inside of a plugin but does inside functions.php?

I have a project to complete where sites within a WordPress Multisite blog will automatically add users to the corresponding sites (where the plugin is enabled)

I hope I worded that correctly.

Read More

The problem: The wpmu_new_user hook does not fire inside of a plugin but WILL inside of functions.php

This is my code:

 add_action( 'wpmu_new_user', 'register_hack_action', 10, 1 );
 add_action( 'wpmu_activate_user', 'register_hack_action', 10, 1);

 function register_hack_action( $user_id ) {

$this_id = get_current_blog_id();

if ( !defined('ABSPATH') ) {
    // do nothing
} else {
    include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); 
}

$blog_list = get_blog_list( 0, 'all' );
foreach ($blog_list AS $blog) {
    switch_to_blog($blog['blog_id']);
    if ( is_plugin_active( 'register-hack/register-hack.php' ) ) {
        // add user to blog
        add_user_to_blog($blog['blog_id'], $user_id, 'subscriber');
    }       
}   
 }

This works perfectly fine when you add the snippet to functions.php. But when you add it to a plugin (which goes into wp-content/plugins) and then is activated on certain sites, just will not work. if you can try it for yourself you’ll see what i mean.. I don’t understand why it will not work. I need it to be inside of the plugin and work.

Related posts

Leave a Reply

1 comment

  1. Only some extensive debugging could answer this… But this kind of stuff is better placed inside a Must Use plugin.

    Must-use plugins (a.k.a. mu-plugins) are plugins installed in a special directory inside the content folder and which are automatically enabled on all sites in the installation. Must-use plugins do not show in the default list of plugins on the Plugins page of wp-admin – although they do appear in a special Must-Use section – and cannot be disabled except by removing the plugin file from the must-use directory, which is found in wp-content/mu-plugins by default.

    I don’t understand why you’re using that include_once, please, test it removing that.


    Especulations:

    • as a normal plugin, it should be Network Activated and try to encapsulate the actions with:

      add_action( 'plugins_loaded', function() {
           add_action( 'wpmu_new_user', 'register_hack_action', 10, 1 );
           add_action( 'wpmu_activate_user', 'register_hack_action', 10, 1);
      });
      
    • maybe you’re putting inside the main site theme?