|Posted: Friday Feb 15th, 2013 at 5:46 pm #41903|
I need to know if a user has ANY custom capabilities so I can display some default text for a user that has no capabilities assigned. Here’s how to do that…
First, we know that the custom capabilities are inside the s2member “capabilities” array and we extract that array using the get_user_option() function. That array contains key-value pairs for, among other things, the custom capabilities.
For example, if the logged-in user has 2 custom capabilities “music” and “videos” assigned, I will use the following PHP code and the resulting array will conceptually look like this…
Note above that when any custom capability is present, the sub-string “s2member_ccap” is present as a key somewhere in this array, at least once.
The next step is to extract the “key” portion of the key-value pairs because the “value” for a custom capability is always going to be “1”, meaning that “this custom capability is assigned”. So we use the PHP function “array_keys()” to extract an array of just the keys present in this array.
Next, we want to create a long string of all the keys in that array so that we can search for the presence of the “s2member_ccap” sub-string that will be present if any custom capability is assigned, so we use the PHP “implode()” function to create a comma-separated list of all those keys.
Finally, we use the PHP “strpos()” function to search for that “s2member_ccap” sub-string. If this function returns a value, it is the position in the string where that sub-string first occurs. Here’s the important thing – if the sub-string is not found, strpos() returns a Boolean FALSE and that’s what we’re really looking for.
One last PHP note – we use the ‘===’ operator for testing because there are cases where the numeric return value of strpos() could evaluate to a FALSE condition, and using that operator forces the comparison to test exactly for the Boolean type of false.
After that windy and detailed explanation, here’s the full code that would go on the page where you need it…
Note that the first 3 functions are all coded on one line as the return of one function feeds into the argument of the next function. Also, this is not the only way to do this; you can use other PHP constructs such as a FOREACH statement to iterate through the keys, etc. I copied the above code right out of the page where I am using it.
- s2Member® Products