Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MaximeCulea/c24608b889e84e15b58ab6f5e209ad8d to your computer and use it in GitHub Desktop.
Save MaximeCulea/c24608b889e84e15b58ab6f5e209ad8d to your computer and use it in GitHub Desktop.
Check user capabilities
<?php
add_action( 'init', function() {
$check_list_of_caps = [ 'custom_capability_one', 'custom_capability_two', 'manage_options' ];
// Test one
$time_start = microtime( true );
// Get current user caps
$all_users_caps = wp_get_current_user()->allcaps;
// Check against wanted ones
$has_cap = array_intersect( $check_list_of_caps, array_keys( $all_users_caps ) );
// Empty cap
$has_cap = ?: false;
// End test one
$time_end = microtime( true );
echo '<b>Total Execution Time test 1:</b> ' . ( $time_end - $time_start );
echo ' - ' . implode( ',', $has_cap );
// Test two
$time_start = microtime( true );
// Check user roles against a list, return after first one
function current_user_can_array( $list ) {
foreach ( $list as $cap ) {
if ( current_user_can( $cap ) ) {
return $cap;
}
}
return false;
}
$has_cap = current_user_can_array( $check_list_of_caps );
// end test 2
$time_end = microtime( true );
echo '<br /><b>Total Execution Time test 2:</b> ' . ( $time_end - $time_start );
echo ' - ' . $has_cap;
die();
});
@MaximeCulea
Copy link
Author

MaximeCulea commented Jul 5, 2019

First approach is always almost twice quicker :

  • allcaps with native php functions : 4.39E-5 - manage_options
  • current_user_can with a foreach loop : 7.09E-5 - manage_options

It is due to the fact that natives php functions, especially for arrays, are made in deep languages (C& C++), which is quicker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment