Skip to content

Performance issue: add_cap() is called repeatedly on admin_init hook #373

@haldais

Description

@haldais

Hello,

I noticed a performance issue regarding how custom capabilities are assigned in the plugin.

In classes/class-blocks.php, the add_role_caps method is hooked to admin_init:

  add_action( 'admin_init', array( $this, 'add_role_caps' ) );

This means that add_cap() is executed every time admin_init fires. Since admin_init is also triggered on every frontend AJAX request (admin-ajax.php), this causes
unnecessary overhead and redundant database checks/updates for every single AJAX call on the frontend.

Suggested Solution:
According to WordPress best practices, capabilities only need to be added once.
Could you please consider moving the capability assignment to the register_activation_hook or plugin migration routine?

Alternatively, adding a simple guard clause inside add_role_caps() would solve the performance hit:

    1 public function add_role_caps() {
    2     global $wp_roles;
    3
    4     if ( isset( $wp_roles ) ) {
    5         // Prevent redundant executions
    6         $admin_role = $wp_roles->get_role( 'administrator' );
    7         if ( $admin_role && $admin_role->has_cap( 'edit_lazyblock' ) ) {
    8             return; 
    9         }
   10
   11         $wp_roles->add_cap( 'administrator', 'edit_lazyblock' );
   12         // ... (other capabilities)
   13     }
   14 }

Thank you for your great work on this plugin!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions