PHPackages                             mzeahmed/wp-toolkit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mzeahmed/wp-toolkit

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mzeahmed/wp-toolkit
===================

A PHP library with useful and reusable functions for WordPress.

1.0.15(7mo ago)0716MITPHPPHP &gt;=8.1

Since Jan 24Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/mzeahmed/wp-toolkit)[ Packagist](https://packagist.org/packages/mzeahmed/wp-toolkit)[ RSS](/packages/mzeahmed-wp-toolkit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (26)Used By (0)

WP ToolKit
==========

[](#wp-toolkit)

**WP ToolKit** is a PHP library that simplifies WordPress development by providing reusable classes to handle common operations :

- AJAX requests
- Database operations
- and more...

Installation
------------

[](#installation)

```
composer require mzeahmed/wp-helpers
```

Then include Composer's autoloader in your project:

```
require_once 'vendor/autoload.php';
```

Features
--------

[](#features)

1. [AJAX Requests](#ajax-requests)
2. [Database Operations](#database-operations)
3. [User Activity Monitoring](#user-activity-monitoring)
4. [Data Sanitization](#data-sanitization)5[HTTP Client](#http-client)

Ajax Requests
-------------

[](#ajax-requests)

The `Ajax` utility class simplifies working with AJAX in WordPress by providing methods for registering AJAX actions, validating requests, and sending JSON responses.

### Features

[](#features-1)

- Register AJAX Actions: Supports both authenticated (wp\_ajax\_) and public (wp\_ajax\_nopriv\_) actions.
- Send JSON Responses: Easily send success or error responses to the client.
- Nonce Validation: Verifies nonces to ensure request authenticity.
- Error Logging: Logs AJAX errors when WP\_DEBUG is enabled.

### Usage

[](#usage)

#### 1. Register an AJAX Action

[](#1-register-an-ajax-action)

```
use MzeAhmed\WpToolKit\Utils\Ajax;

Ajax::register('my_action', 'my_callback');

function my_callback()
{
    $data = [
        'message' => 'Action executed successfully!',
        'additional_info' => 'Extra data here'
    ];

    Ajax::sendJsonSuccess('Success!', $data);
}
```

#### 2. Send JSON Responses

[](#2-send-json-responses)

Use the `sendJsonSuccess` and `sendJsonError` methods to send standardized JSON responses:

```
Ajax::sendJsonSuccess('Success message', ['data' => 'value']);
Ajax::sendJsonError('Error message', ['error' => 'reason']);
```

#### 3. Nonce Validation

[](#3-nonce-validation)

Verify nonces to ensure that AJAX requests are secure:

```
Ajax::verifyNonce('nonce_field_name', 'action_name');
```

Need to define theses constants in the application: `AJAX_SECURITY_NONCE_ACTION` and `AJAX_SECURITY_NONCE`.

```
define('AJAX_SECURITY_NONCE_ACTION', 'my_action');
define('AJAX_SECURITY_NONCE', 'nonce_field_name');
```

And use wp\_localize\_script to pass the nonce to the client side.

```
wp_localize_script('your-script-handle', 'ajax_object', [
    'ajax_url' => admin_url('admin-ajax.php'),
    AJAX_SECURITY_NONCE => wp_create_nonce(AJAX_SECURITY_NONCE_ACTION),
]);
```

In the client side, you can use the nonce like this:

```
fetch(ajax_object.ajax_url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-WP-Nonce': ajax_object.nonce_field_name
    },
    body: new URLSearchParams({
        action: 'my_action',
        data: 'value'
    })
})
```

Database Operations
-------------------

[](#database-operations)

- **Abstract Repository:** Base class for implementing the repository pattern with `$wpdb`.
- **Pagination Support:** Easily paginate database results.
- **Bulk Operations:** Perform bulk inserts, updates, and deletes.
- **Transaction Management:** Start, commit, and rollback database transactions.
- **Error Logging:** Automatically log and debug database errors.
- **Dynamic Query Building:** Flexible support for building dynamic `WHERE` and `JOIN` clauses.

### Usage

[](#usage-1)

#### 1. Implement a Repository

[](#1-implement-a-repository)

Create a repository class that extends the `AbstractRepository` class. For example:

```
namespace YourNamespace\Repositories;

use Mzeahmed\WpToolKit\Database\AbstractRepository;

class YourCustomRepository extends AbstractRepository
{
    public function __construct()
    {
        parent::__construct();
        $this->tableName = $this->wpdbPrefix . 'your_table_name';
    }

    public function findActiveItems(): array
    {
        return $this->findByCriteria(['status' => 'active']);
    }
}
```

#### 2. Use the Repository

[](#2-use-the-repository)

In your WordPress plugin or theme:

```
use YourNamespace\Repositories\YourCustomRepository;

$repository = new YourCustomRepository();
$activeItems = $repository->findActiveItems();
```

#### 3. Bulk Operations

[](#3-bulk-operations)

Perform bulk inserts, updates, or deletes:

```
// Bulk insert example
$repository->bulkInsert([
    ['column1' => 'value1', 'column2' => 'value2'],
    ['column1' => 'value3', 'column2' => 'value4'],
]);

// Bulk delete example
$repository->bulkDelete('id', [1, 2, 3]);
```

#### 4. Transactions

[](#4-transactions)

Manage transactions to ensure data consistency:

```
$repository->beginTransaction();

try {
    $repository->insert(['column1' => 'value1']);
    $repository->update(['column2' => 'value2'], ['id' => 1]);
    $repository->commit();
} catch (\Exception $e) {
    $repository->rollback();
    error_log($e->getMessage());
}
```

User Activity Monitoring
------------------------

[](#user-activity-monitoring)

The `UserActivityMonitor` class helps track user activity and determine online/offline status.

### Features

[](#features-2)

- Track User Activity: Monitor user activity and update the last seen timestamp.
- Check Online Status: Determine if a user is online within a specified margin.
- Retrieve Online Users: Get a list of all users currently online.
- Identify Recently Offline Users: Retrieve users who recently went offline.

### Usage

[](#usage-2)

#### 1. Update User Activity

[](#1-update-user-activity)

```
use MzeAhmed\WpToolKit\UserActivityMonitor;

$monitor = new UserActivityMonitor();
$monitor->updateStatus($userId);
```

#### 2. Check Online Status

[](#2-check-online-status)

```
$isOnline = $monitor->isUserOnline($userId);

if ($isOnline) {
    echo "User $userId is online.";
} else {
    echo "User $userId is offline.";
}
```

#### 3. Retrieve Online Users

[](#3-retrieve-online-users)

```
$onlineUsers = $monitor->getOnlineUsers();

foreach ($onlineUsers as $user) {
    echo "User $user->ID is online.";
}
```

#### 4. Identify Recently Offline Users

[](#4-identify-recently-offline-users)

```
$recentlyOfflineUsers = $monitor->getRecentlyOfflineUsers();

foreach ($recentlyOfflineUsers as $user) {
    echo "User $user->ID recently went offline.";
}
```

Data Sanitization
-----------------

[](#data-sanitization)

The `Sanitizer` class provides static methods to clean user input and ensure data safety in WordPress environments.

### Features

[](#features-3)

- ✅ Sanitize strings, emails, URLs, and textarea contents
- 🔁 Sanitize arrays and nested arrays
- 🎯 Apply custom sanitization rules per field

### Supported Rules

[](#supported-rules)

RuleDescription`text`Uses `sanitize_text_field()``email`Uses `sanitize_email()``url`Uses `esc_url_raw()``textarea`Uses `sanitize_textarea_field()`### Usage

[](#usage-3)

#### 1. Sanitize a single value or array

[](#1-sanitize-a-single-value-or-array)

```
use MzeAhmed\WpToolKit\Utils\Sanitizer;

$cleanText = Sanitizer::text(' John ');
// returns 'John'

$cleanEmailArray = Sanitizer::email(['  a@a.com ', 'b@b.com ']);
// returns ['a@a.com', 'b@b.com']
```

### 2. Recursively sanitize text values in nested arrays

[](#2-recursively-sanitize-text-values-in-nested-arrays)

```
$dirtyArray = [
    'name' => ' John ',
     'meta' => [
        'city' => ' Paris ',
        'desc' => " Hello\nWorld "
    ]
];

$clean = Sanitizer::recursiveText($raw);
// returns [
//   'name' => 'John',
//   'meta' => [
//     'city' => 'Paris',
//     'desc' => "Hello\nWorld"
//   ]
// ]
```

### 3. Apply custom sanitization rules

[](#3-apply-custom-sanitization-rules)

```
$data = [
    'name' => ' John Doe ',
    'email' => ' john@example.com ',
    'website' => ' https://example.com ',
    'bio' => " Hello\nI'm John "
];

$rules = [
    'name' => 'text',
    'email' => 'email',
    'website' => 'url',
    'bio' => 'textarea'
];

$cleaned = Sanitizer::byRules($data, $rules);
// returns [
//   'name' => 'John Doe',
//   'email' => 'john@example.com',
//   'website' => 'https://example.com',
//   'bio' => "Hello\nI'm John"
// ]
```

HTTP Client
-----------

[](#http-client)

The `HttpClient` class simplifies making HTTP requests in WordPress using `wp_remote_*` functions. It supports GET, POST, PUT, DELETE (and PATCH) and automatically decodes JSON responses.

### Features

[](#features-4)

- Perform requests with `wp_remote_get`, `wp_remote_post`, etc.
- Supports safe URLs with `reject_unsafe_urls`
- Automatically decodes JSON response bodies
- Unified interface for REST APIs

### Usage

[](#usage-4)

#### 1. Initialize the client

[](#1-initialize-the-client)

```
use MzeAhmed\WpToolKit\Http\HttpClient;

$client = new HttpClient();
```

#### 2. Make a GET request

[](#2-make-a-get-request)

```
$response = $client->get('https://jsonplaceholder.typicode.com/posts');

if (is_wp_error($response)) {
    error_log($response->get_error_message());
} else {
    var_dump($response); // array of posts
}
```

#### 3. Make a POST request

[](#3-make-a-post-request)

```
$response = $client->post('https://example.com/api/data', [
    'name' => 'John',
    'email' => 'john@example.com'
]);
```

### 4. Use safe mode (rejects unsafe URLs)

[](#4-use-safe-mode-rejects-unsafe-urls)

```
$response = $client->get('http://example.com', [], true); // safe mode enabled
```

📖 API Reference
---------------

[](#-api-reference)

### `MzeAhmed\WpToolKit\Http\HttpClient`

[](#mzeahmedwptoolkithttphttpclient)

MethodDescriptionReturn Type`get()`Perform an HTTP GET request`array`post()`Perform an HTTP POST request`array`put()`Perform an HTTP PUT request`array`delete()`Perform an HTTP DELETE request`array- All methods accept:
    - `$url` *(string)* – The endpoint to query
    - `$args` *(array)* – Optional arguments (headers, timeout, etc.)
    - `$safe` *(bool)* – Enable WordPress URL validation with `reject_unsafe_urls`

> Automatically decodes the JSON response body with `json_decode(..., JSON_THROW_ON_ERROR)`.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance64

Regular maintenance activity

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~11 days

Recently: every ~42 days

Total

24

Last Release

220d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.3

1.0.5.6PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/357c2307fae6dd20cc568475b9e248d6796752db9ffab754efcffde06095c493?d=identicon)[mzeahmed](/maintainers/mzeahmed)

---

Top Contributors

[![mzeahmed](https://avatars.githubusercontent.com/u/45328592?v=4)](https://github.com/mzeahmed "mzeahmed (75 commits)")

### Embed Badge

![Health badge](/badges/mzeahmed-wp-toolkit/health.svg)

```
[![Health](https://phpackages.com/badges/mzeahmed-wp-toolkit/health.svg)](https://phpackages.com/packages/mzeahmed-wp-toolkit)
```

###  Alternatives

[bear/ace

Ace online editor utility

104.0k1](/packages/bear-ace)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
