PHP code example of wpboilerplate / wpb-access-control

1. Go to this page and download the library: Download wpboilerplate/wpb-access-control library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wpboilerplate / wpb-access-control example snippets




use WPBoilerplate\AccessControl\AccessControlManager;

// File scope — available to all hooks below via `use ( $manager )`.
$manager = new AccessControlManager( 'my_plugin_access_control_providers' );

> $manager = null;
> add_action( 'plugins_loaded', function () use ( &$manager ) {
>     $manager = new AccessControlManager( 'my_plugin_access_control_providers' );
> } );
> // All subsequent hooks must also use `&$manager`.
> 

add_action( 'rest_api_init', function () use ( $manager ) {
    $manager->register_rest_api();
} );


/**
 * Plugin Name: My Plugin
 */

use WPBoilerplate\AccessControl\AccessControlManager;

// 1. Require Composer autoloader.
_plugin_access_control_providers' );

// 3. Expose the REST API.
add_action( 'rest_api_init', function () use ( $manager ) {
    $manager->register_rest_api();
} );

// 4. Register an admin settings page and capture its hook suffix.
$settings_hook = null;
add_action( 'admin_menu', function () use ( &$settings_hook ) {
    // add_submenu_page() returns the hook suffix needed in admin_enqueue_scripts.
    $settings_hook = add_submenu_page(
        'options-general.php',         // parent menu slug
        'My Plugin Settings',          // page title
        'My Plugin',                   // menu title
        'manage_options',              // capability
        'my-plugin-settings',          // menu slug
        function () {
            echo '<div class="wrap">';
            echo '<h1>My Plugin Settings</h1>';
            // 5. Mount point — the React component attaches here automatically.
            echo '<div id="wpb-access-control"></div>';
            echo '</div>';
        }
    );
} );

// 6. Enqueue the built React UI assets only on the settings page.
add_action( 'admin_enqueue_scripts', function ( string $hook ) use ( &$settings_hook ) {
    if ( $hook !== $settings_hook ) {
        return;
    }

    $asset_file = 

$allowed = $manager->user_has_access(
    get_current_user_id(),   // int  — 0 = unauthenticated
    'my-namespace',          // string — your plugin's namespace
    'my-resource'            // string — the specific resource key
);

if ( ! $allowed ) {
    wp_die( 'Access denied.', 403 );
}

// Capture the hook suffix when registering the page.
$page_hook = add_submenu_page( /* … */ );

add_action( 'admin_enqueue_scripts', function ( string $hook ) use ( $page_hook ) {

    // Only load on the page where you need it.
    if ( $hook !== $page_hook ) {
        return;
    }

    $asset_file = wp-api-fetch', 'wp-element']
        $asset_file['version'],
        true
    );

    wp_enqueue_style(
        'wpb-ac-ui',
        plugin_dir_url( __FILE__ )
            . 'vendor/wpboilerplate/wpb-access-control/assets/build/index.css',
        [],
        $asset_file['version']
    );

    // Pass configuration to the component via window.wpbAcConfig.
    wp_localize_script( 'wpb-ac-ui', 'wpbAcConfig', [
        'namespace'   => 'my-namespace',
        'resourceKey' => 'my-resource',
        'restApiRoot' => get_rest_url(),
        'nonce'       => wp_create_nonce( 'wp_rest' ),
        // Optional overrides:
        'title'       => 'Access Control',
        'description' => 'Control which users may access this feature.',
        'saveLabel'   => 'Save Access Control',
    ] );
} );

add_action( 'my_plugin_settings_page', function () {
    echo '<div id="wpb-access-control"></div>';
} );

use WPBoilerplate\AccessControl\Database\Rule\RuleQuery;

$query = new RuleQuery();

// Read the current rule.
$rule = $query->get_rule( 'my-namespace', 'my-resource' );
// → ['key' => 'wp_role', 'value' => ['editor', 'author']]
// → ['key' => '',        'value' => []]   when no rule is set

// Save a rule (inputs are sanitized internally).
$query->set_rule( 'my-namespace', 'my-resource', 'wp_role', ['editor', 'author'] );

// Allow everyone.
$query->set_rule( 'my-namespace', 'my-resource', 'everyone', [] );

// Clear a rule (reverts to "no restriction configured").
$query->clear_rule( 'my-namespace', 'my-resource' );

// Plugin uninstall — delete all rows for your namespace.
$query->purge_namespace( 'my-namespace' );

$rule = $manager->get_query()->get_rule( 'my-namespace', 'my-resource' );

$nonce = wp_create_nonce( 'wp_rest' );

// Read
$response = wp_remote_get(
    rest_url( 'wpb-ac/v1/rules/my-namespace/my-resource' ),
    [ 'headers' => [ 'X-WP-Nonce' => wp_create_nonce( 'wp_rest' ) ] ]
);
$rule = json_decode( wp_remote_retrieve_body( $response ), true );

// Set
wp_remote_request(
    rest_url( 'wpb-ac/v1/rules/my-namespace/my-resource' ),
    [
        'method'  => 'PUT',
        'headers' => [
            'Content-Type' => 'application/json',
            'X-WP-Nonce'   => wp_create_nonce( 'wp_rest' ),
        ],
        'body' => wp_json_encode( [ 'ac_key' => 'wp_role', 'ac_options' => [ 'editor' ] ] ),
    ]
);

add_filter( 'wpb_access_control_rest_permission', function ( bool $can, WP_REST_Request $request ): bool {
    // Allow editors to read rules, but only admins to write.
    if ( 'GET' === $request->get_method() ) {
        return current_user_can( 'edit_posts' );
    }
    return $can;
}, 10, 2 );

add_filter( 'wpb_access_control_can_save', function ( bool $can, string $namespace, string $key, int $user_id ): bool {
    return 'my-namespace' === $namespace;
}, 10, 4 );

add_action( 'wpb_access_control_denied', function (
    int    $user_id,
    string $namespace,
    string $key,
    string $ac_key,
    array  $options
): void {
    error_log( "Access denied — user:{$user_id} {$namespace}/{$key}" );
}, 10, 5 );

add_action( 'wpb_access_control_saved', function (
    string $namespace,
    string $key,
    string $ac_key,
    array  $ac_options,
    int    $user_id
): void {
    // Audit log, cache bust, etc.
}, 10, 5 );

add_filter( 'my_plugin_access_control_providers', function ( array $providers ): array {
    $providers[] = new My\Plugin\MembershipProvider();
    return $providers;
} );

namespace My\Plugin;

use WPBoilerplate\AccessControl\AbstractProvider;

class MembershipProvider extends AbstractProvider {

    public function get_id(): string    { return 'my_membership'; }
    public function get_label(): string { return __( 'Membership Level', 'my-plugin' ); }

    public function get_options(): array {
        return [
            [ 'id' => 'gold',   'label' => 'Gold'   ],
            [ 'id' => 'silver', 'label' => 'Silver' ],
        ];
    }

    public function user_has_access( int $user_id, array $selected_options ): bool {
        return in_array( my_get_membership_level( $user_id ), $selected_options, true );
    }

    public function is_available(): bool {
        return function_exists( 'my_get_membership_level' );
    }
}

use WPBoilerplate\AccessControl\WpUserProvider;

// Search by login, email, or display name.
$results = WpUserProvider::search_users( 'jane', 10 );
// → [['id'=>'5','login'=>'jane','email'=>'[email protected]','display_name'=>'Jane Doe'], ...]

// Hydrate stored IDs → display data (useful for custom UIs).
$users = WpUserProvider::get_users_by_ids( ['5', '42'] );

// uninstall.php
( new \WPBoilerplate\AccessControl\Database\Rule\RuleQuery() )
    ->purge_namespace( 'my-namespace' );