Points Logs Viewing Restrictions API

WordPoints 2.2.0 introduced the Points Logs Viewing Restrictions API, to provide a better way to hide points logs from unprivileged users. The API consists of a children class registry that is a child of the points -> logs app. The restrictions can be registered for a particular log type by specifying the log type’s slug as the parent slug for the class, or for all log types by using the parent slug 'all'.

An example use is when a certain type of log is related to posts, and so it is necessary to hide the logs of that type that relate to private posts.

Interface #

Each restriction class must implement the WordPoints_Points_Logs_Viewing_RestrictionI interface, which requires the following methods:

  • __construct( $log ) — The object should expect to be constructed with a log object.
  • get_description() — Returns a description of the restriction, or an array of descriptions if necessary. Each description should follow the format “This log entry is only visible to users who can {do this}.” For example, “This log entry is only visible to users who can view the post.”
  • applies() — This method must return a boolean value indicating whether or not the restriction applies to the particular log in question. If this restriction was for non-public posts, we’d check if the post that the log was related to had a non-public status, and if so we’d return true.
  • user_can( $user_id ) — Determines whether a particular user should be allowed to view this log. Using the same example as before, we’d check if the post was non-public, and if so, we’d check if the user could read it using WordPress’s capabilities API.

Example Class #

Here is the core implementation of the Read Post viewing restriction:

As you can see, much of the logic is in the constructor, to avoid duplication between applies() and user_can().

Usage #

As you can see, the restrictions app provides a get_restriction() method, which returns an object that implements the restriction interface. This restriction object is actually a wrapper that encloses all of the restriction objects that apply to that type of log, if any. This makes it simple for you to determine the visibility of a points log without having to possibly loop over several restrictions, since that is handled internally within the wrapper.

Registration #

Note that often you will want to register entity restrictions, rather than adding new restrictions here. If you are adding restrictions related to points logs that originate with the Hooks API, you probably don’t need to register them here, since there is already a generic restriction that automatically integrates the entity restrictions API with the points logs for all logs that originate from the Hooks API.

In any other case, however, you can register restrictions like this: