Created
June 27, 2019 13:14
-
-
Save MaximeCulea/c24608b889e84e15b58ab6f5e209ad8d to your computer and use it in GitHub Desktop.
Check user capabilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First approach is always almost twice quicker :
It is due to the fact that natives php functions, especially for arrays, are made in deep languages (C& C++), which is quicker.