WordPress Core

kaiseki/wp-context

Composable WordPress context filters (current user, post type, page template, content).

A context filter is any object implementing ContextFilterInterface__invoke(?WP_Post $post = null): bool. It answers a yes/no question about the current request (or a given post): “is this a page?”, “can the current user edit posts?”, “does the content contain this block?”. ContextFilterPipeline ANDs several filters together (and is itself a filter, so pipelines nest), which makes it easy to gate behavior on a combination of conditions.

Installation

composer require kaiseki/wp-context

Requires PHP 8.2 or newer.

Usage

use Kaiseki\WordPress\Context\Filter\ContextFilterPipeline;
use Kaiseki\WordPress\Context\Filter\CurrentUserCan;
use Kaiseki\WordPress\Context\Filter\IsPostType;

$filter = new ContextFilterPipeline(
    new IsPostType('page'),
    new CurrentUserCan('edit_pages'),
);

if ($filter($post)) {
    // the request is a 'page' AND the current user can edit pages
}

Each filter is invokable on its own and accepts an optional WP_Post; when omitted it resolves the current post / global context. ContextFilterPipeline returns false as soon as one filter fails.

Included filters

Filter (and its negation)True when
ContextFilterPipelineevery contained filter passes
IsPostType / IsNotPostTypethe post matches the given post type
IsFrontPagethe post is the configured front page
IsPageTemplate / IsNotPageTemplatethe post uses the given page template
IsPageTemplateFileName / IsNotPageTemplateFileNamethe post’s page template matches the given file name
IsUserLoggedIn / IsUserNotLoggedIna user is logged in
CurrentUserCan / CurrentUserCanNotthe current user has the given capability
CurrentUserHasRole / CurrentUserHasNotRolethe current user has the given role
CurrentUserHasEmail / CurrentUserHasNotEmailthe current user has the given email
CurrentUserIsAdmin / CurrentUserIsNotAdminthe current user is an administrator
ContentContainsBlock / ContentDoesNotContainBlockthe post content contains the given block
ContentContainsRegex / ContentDoesNotContainRegexthe post content matches the given pattern

Write your own by implementing ContextFilterInterface:

use Kaiseki\WordPress\Context\Filter\ContextFilterInterface;
use WP_Post;

final class IsSticky implements ContextFilterInterface
{
    public function __invoke(?WP_Post $post = null): bool
    {
        return $post !== null && is_sticky($post->ID);
    }
}

Development

composer install
composer check   # check-deps, cs-check, phpstan

License

MIT — see LICENSE.

Previous
kaiseki/wp-cli-util