PHPackages                             wpdesk/wp-mutex - 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. wpdesk/wp-mutex

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

wpdesk/wp-mutex
===============

Library for locking in Wordpress.

1.1(7y ago)043.0k↓52.6%5MITPHPPHP &gt;=5.6CI failing

Since Oct 16Pushed 2mo agoCompare

[ Source](https://github.com/WP-Desk/wp-mutex)[ Packagist](https://packagist.org/packages/wpdesk/wp-mutex)[ Docs](https://gitlab.com/wpdesk/wp-mutex)[ RSS](/packages/wpdesk-wp-mutex/feed)WikiDiscussions master Synced 2w ago

READMEChangelogDependencies (6)Versions (4)Used By (5)

WP Mutex
========

[](#wp-mutex)

[![pipeline status](https://camo.githubusercontent.com/6571872f256550fa2555838ec740630541b74b00a4576a86b4133792b644c987/68747470733a2f2f6769746c61622e636f6d2f77706465736b2f77702d6d757465782f6261646765732f6d61737465722f706970656c696e652e737667)](https://gitlab.com/wpdesk/wp-mutex/pipelines)[![coverage report](https://camo.githubusercontent.com/db1fc1ef52a1803e27d2f6b498ce8b828390310b7dcb96d321f82fb727fe5e33/68747470733a2f2f6769746c61622e636f6d2f77706465736b2f77702d6d757465782f6261646765732f6d61737465722f636f7665726167652e737667)](https://gitlab.com/wpdesk/wp-mutex/commits/master)[![Latest Stable Version](https://camo.githubusercontent.com/95e15cac56b1fc4da392e183fef7f33ed87346cdd0e7dcfa05ea534dbedae5dd/68747470733a2f2f706f7365722e707567782e6f72672f77706465736b2f77702d6d757465782f762f737461626c65)](https://packagist.org/packages/wpdesk/wp-mutex)[![Total Downloads](https://camo.githubusercontent.com/cc980db8bc8b5ac0e1d38afc5fa0655e401d431fb0652e48b231b183d542fbda/68747470733a2f2f706f7365722e707567782e6f72672f77706465736b2f77702d6d757465782f646f776e6c6f616473)](https://packagist.org/packages/wpdesk/wp-mutex)[![Latest Unstable Version](https://camo.githubusercontent.com/4063c453c7c38e8e8027cf389daaf253189bba125fa2c6b0be47dd5f12a3a9a0/68747470733a2f2f706f7365722e707567782e6f72672f77706465736b2f77702d6d757465782f762f756e737461626c65)](https://packagist.org/packages/wpdesk/wp-mutex)[![License](https://camo.githubusercontent.com/784333f40d638b38bfc3c2a02a0e9a031bd37e5afd3a9fdfd9e225c8be166c3d/68747470733a2f2f706f7365722e707567782e6f72672f77706465736b2f77702d6d757465782f6c6963656e7365)](https://packagist.org/packages/wpdesk/wp-mutex)

`wp-mutex` is a robust and lightweight PHP library designed for WordPress plugins to handle concurrency and prevent race conditions. It ensures that critical sections of your code (such as checkout operations, payment webhook processing, or API syncs) are executed by only one process at a time.

---

Requirements
------------

[](#requirements)

- PHP 5.6 or later.
- WordPress environment (depends on the `$wpdb` global object and database tables).

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

[](#installation)

### Via Composer (Recommended)

[](#via-composer-recommended)

Run the following command in your project directory:

```
composer require wpdesk/wp-mutex
```

To load the library in your plugin, use the Composer autoloader:

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

### Manual Installation

[](#manual-installation)

If you prefer not to use Composer, you can download the latest release and include the `src/init.php` file manually:

```
require_once '/path/to/wp-mutex/src/init.php';
```

---

How It Works
------------

[](#how-it-works)

The library offers two main mutex implementations depending on your concurrency requirements:

### 1. MySQL Session Lock (`WordpressMySQLLockMutex`)

[](#1-mysql-session-lock-wordpressmysqllockmutex)

- **Under the hood:** Uses MySQL's native `GET_LOCK()` and `RELEASE_LOCK()` functions.
- **Best for:** Server-wide locks on abstract resources or operations.
- **Behavior:** Locks are tied to the active MySQL connection session. If the PHP process crashes or the database connection drops, MySQL automatically releases the lock, preventing deadlocks.

### 2. WordPress Postmeta Lock (`WordpressPostMutex`)

[](#2-wordpress-postmeta-lock-wordpresspostmutex)

- **Under the hood:** Inserts atomic lock records into the WordPress `wp_postmeta` table.
- **Best for:** Operations associated with a specific WordPress Post ID (e.g., preventing double-processing on a WooCommerce Order).
- **Behavior:** Locks are persistent and exist until they expire (based on the defined timeout) or are explicitly released. This is useful for scenarios where database connections might drop but the resource must remain locked.

---

Usage Guide
-----------

[](#usage-guide)

### 1. Using Global Helper Functions

[](#1-using-global-helper-functions)

For quick integration, you can use the global procedural helper functions. These use static storage (`StaticMutexStorage`) to track active locks.

```
$lock_name = 'my_critical_operation';

// Try to acquire the lock (defaults to MySQL lock with a 5-second wait timeout)
if ( wpdesk_acquire_lock( $lock_name, $waitForLockTimeout = 5 ) ) {
    try {
        // Do your concurrency-sensitive tasks here
    } finally {
        // Always release the lock in a finally block to ensure it's freed
        wpdesk_release_lock( $lock_name );
    }
} else {
    // Handle lock acquisition failure
    echo 'Unable to acquire lock!';
}
```

### 2. Object-Oriented Usage (MySQL Lock)

[](#2-object-oriented-usage-mysql-lock)

You can instantiate the `WordpressMySQLLockMutex` directly for more fine-grained control:

```
use WPDesk\Mutex\WordpressMySQLLockMutex;

$mutex = new WordpressMySQLLockMutex( 'my_unique_lock_key', $waitForLockTimeout = 10 );

if ( $mutex->acquireLock() ) {
    try {
        // Critical logic
    } finally {
        $mutex->releaseLock();
    }
}
```

### 3. Object-Oriented Usage (WordPress Postmeta Lock)

[](#3-object-oriented-usage-wordpress-postmeta-lock)

Use `WordpressPostMutex` when you need to lock operations related to a specific Post ID:

```
use WPDesk\Mutex\WordpressPostMutex;

$post_id = 123; // ID of the WordPress post or WooCommerce order
$lock_name = 'payment_processing';
$lock_expiry_timeout = 30; // Lock expires automatically in 30 seconds
$wait_for_lock_timeout = 5; // Wait up to 5 seconds to acquire the lock

$mutex = new WordpressPostMutex( $post_id, $lock_name, $lock_expiry_timeout, $wait_for_lock_timeout );

if ( $mutex->acquireLock() ) {
    try {
        // Process order / post changes securely
    } finally {
        $mutex->releaseLock();
    }
}
```

### 4. Locking WooCommerce Orders

[](#4-locking-woocommerce-orders)

Both mutex implementations support helper factory methods/functions for WooCommerce orders.

#### Using MySQL Lock from WooCommerce Order:

[](#using-mysql-lock-from-woocommerce-order)

```
use WPDesk\Mutex\WordpressMySQLLockMutex;

// Using the global helper:
$mutex = wpdesk_create_mysql_lock_from_order( $order, $lockName = '_mutex', $waitForLockTimeout = 5 );

// Or using the class factory directly:
$mutex = WordpressMySQLLockMutex::fromOrder( $order, $lockName = '_mutex', $waitForLockTimeout = 5 );

if ( $mutex->acquireLock() ) {
    try {
        // Safe order processing
    } finally {
        $mutex->releaseLock();
    }
}
```

#### Using Postmeta Lock from WooCommerce Order:

[](#using-postmeta-lock-from-woocommerce-order)

```
use WPDesk\Mutex\WordpressPostMutex;

// $order is an instance of \WC_Order
$mutex = WordpressPostMutex::fromOrder( $order, $lock_name = '_mutex', $timeout = 5 );

if ( $mutex->acquireLock() ) {
    try {
        // Safe order processing
    } finally {
        $mutex->releaseLock();
    }
}
```

---

Advanced: Static Storage
------------------------

[](#advanced-static-storage)

When using helper functions (`wpdesk_acquire_lock` / `wpdesk_release_lock`), the library keeps track of active locks in a static storage class: `WPDesk\Mutex\StaticMutexStorage`.

If you try to call `wpdesk_release_lock( $lockName )` for a lock that has not been stored or has already been released, the library will throw a `\WPDesk\Mutex\MutexNotFoundInStorage` exception.

---

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance57

Moderate activity, may be stable

Popularity27

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90.9% 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 ~14 days

Total

3

Last Release

2835d ago

PHP version history (2 changes)1.0PHP &gt;=5.5

1.1PHP &gt;=5.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/16497f8884c0767d3a114cc1cf8daaa639bac052178b03c59d59dfa95569d50b?d=identicon)[dyszczo](/maintainers/dyszczo)

![](https://www.gravatar.com/avatar/e6b9d73e70788735e2d8af0fba63affafdea243effde5eeae3e6fbb1e5d828e6?d=identicon)[grola](/maintainers/grola)

![](https://www.gravatar.com/avatar/97ac8b53a77161e994c106cc2136cf0601d404e5fd4a3295884d692c767636c7?d=identicon)[bjaskulski](/maintainers/bjaskulski)

![](https://www.gravatar.com/avatar/8e4b1bce6dad69911f85ab3abc19f8432db4a34a3b8a27043b90e82eab83e506?d=identicon)[eryk.mika](/maintainers/eryk.mika)

---

Top Contributors

[![seostudio](https://avatars.githubusercontent.com/u/8124521?v=4)](https://github.com/seostudio "seostudio (20 commits)")[![dyszczo](https://avatars.githubusercontent.com/u/1263190?v=4)](https://github.com/dyszczo "dyszczo (2 commits)")

---

Tags

wordpressmutexlock

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/wpdesk-wp-mutex/health.svg)

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

###  Alternatives

[aristath/kirki

Extending the WordPress customizer

1.3k73.1k4](/packages/aristath-kirki)[afragen/git-updater

A plugin to automatically update GitHub, Bitbucket, GitLab, or Gitea hosted plugins, themes, and language packs.

3.3k1.8k](/packages/afragen-git-updater)[tacowordpress/tacowordpress

WordPress custom post types that feel like CRUD models

232.2k](/packages/tacowordpress-tacowordpress)

PHPackages © 2026

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