Skip to main content

How to register a custom condition type?

Vasyl MartyniukLess than 1 minute

AAM provides numerous pre-defined condition types designed to cover a wide range of use cases. However, there are no restrictions on augmenting the existing list with custom types.

Consider this scenario: your website stores a list of writer skills as an array of strings in the user_skills user meta table. You wish to authorize access to edit all posts within the "Science" category for writers possessing the "science" skill, and you prefer to implement fuzzy search functionality within the array of skills to account for misspellings or plurals. A policy for this might be formulated as follows:

{
    "Statement": [
        {
            "Effect": "deny",
            "Resource": "PostType:post:posts",
            "Action": "Edit"
        },
        {
            "Effect": "allow",
            "Resource": "Term:category:science:posts",
            "Action": "Edit",
            "Condition": {
                "FuzzyMatch": {
                    "science": "(*array)${USER_META.user_skills}"
                }
            }
        }
    ]
}

To support the FuzzyMatch condition type, we are going to register a custom type following way:

add_filter('aam_policy_condition_result_filter', function($result, $type, $group, $args) {
    // This function receives following values:
    // - $result = false
    // - $type   = "fuzzymatch" (the condition type get's lowercased before processing)
    // - $group  = [ "science" => ["skill-a", "skill-b", ...] ]
    // - $args   = array or inline arguments. To learn more, refer to the
    //             https://aamportal.com/reference/json-access-policy/marker/args
    if ($type === 'fuzzymatch') {
        // Execute some fuzzy match functionality that checks all conditions
    }

    return $result;
}, 10, 4);