Limiting the number of users

As you can see in the WordPress Option Reference, there’s an option called users_can_register. You can – per default – set it in your (network-)sites settings.

  • 1 => Yes
  • 0 => No

As usual: There’s a filter to intercept that from a plugin.

"option_{$option_name}"

So you can simply attach a callback to this filter and check the amount of users with a WP_User_Query for the get_current_blog_id().

<?php

namespace WPSE;
/** Plugin Name: WPSE (#110036) Limit Total Users per page */
defined( 'ABSPATH' ) or exit;

\add_filter( 'option_users_can_register', 'limit_total_users' );
function limit_total_users( $option )
{
    // Nothing to do here
    if ( 0 === $option )
        return $option;

    static $users = null;
    $limit = 50;

    if ( null === $users )
    {
        $users_query = new \WP_User_Query( array(
            'blog_id' => get_current_blog_id()
        ) );
        $users = $users_query->get_total();
    }

    // Abort if we're above the limit
    if ( $limit > $users )
        return 0;

    return $option;
}

The nice thing about this mini plugin is, that it doesn’t do an additional query if the registration is already turned off.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)