PHPackages                             friedolinfoerder/wp-activerecord - 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. [Database &amp; ORM](/categories/database)
4. /
5. friedolinfoerder/wp-activerecord

ActiveLibrary[Database &amp; ORM](/categories/database)

friedolinfoerder/wp-activerecord
================================

An ActiveRecord implementation for WordPress

v1.0.6(5y ago)237.2k↓58.3%5MITPHPPHP &gt;=5.5.0CI failing

Since Jun 15Pushed 2y ago5 watchersCompare

[ Source](https://github.com/friedolinfoerder/wp-activerecord)[ Packagist](https://packagist.org/packages/friedolinfoerder/wp-activerecord)[ Docs](https://github.com/friedolinfoerder/wp-activerecord)[ RSS](/packages/friedolinfoerder-wp-activerecord/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (8)Used By (0)

WordPress ActiveRecord
======================

[](#wordpress-activerecord)

WordPress ActiveRecord implements the [active record pattern](http://en.wikipedia.org/wiki/Active_record_pattern) to easily retrieve, update and delete rows of database tables without struggling with raw SQL query strings. The goal of this library is to provide a small but yet powerful [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) for the CMS WordPress, which should be easy to implement. Therefore it only consists of two classes: `ActiveRecord` and `Query`:

- The `ActiveRecord` class maps rows to object instances and the columns to object properties.
- The `Query` class provides a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface) to create sql queries.

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

[](#installation)

```
composer require friedolinfoerder/wp-activerecord
```

Usage
-----

[](#usage)

You can use the library in your plugin or directly in your `functions.php` file. All you have to do is to require the `ActiveRecord` class and define your model classes (e.g. `Slideshow`):

```
// create a model class for the table {wp-prefix}slideshows
class Slideshow extends \wp_activerecord\ActiveRecord {
    protected static $table_name = 'slideshows';
}
```

With this you can create new rows, update and save them like this:

```
// create new row
$slideshow = Slideshow::create([
    'title'        => 'Header slideshow',
    'slide_time'   => 3000,
    'slide_effect' => 'fade'
]);

// retrieve by id...
$slideshow = Slideshow::get(1);

// ... and update the row
$slideshow->title = 'New title';
$slideshow->slide_effect = 'slide';
$slideshow->save();
```

API
---

[](#api)

- [Class `ActiveRecord`](#class-activerecord)
    - [Static properties](#static-properties)
        - [Property `$casts`](#property-casts)
    - [Static methods](#static-methods)
        - [Method `create([$attributes])`](#method-createattributes)
        - [Method `delete_by_id($id)`](#method-delete_by_idid)
        - [Method `get([$id])`](#method-getid)
        - [Method `get_{type}_by_{column}($value [, $...])`](#method-get_type_by_columnvalue--)
        - [Method `get_table_name()`](#method-get_table_name)
        - [Method `insert($data)`](#method-insertdata)
        - [Method `query()`](#method-query)
        - [Method `update($column [, $value])`](#method-updatecolumn--value)
        - [Method `wpdb()`](#method-wpdb)
    - [Instance methods](#instance-methods)
        - [Method `delete()`](#method-delete)
        - [Method `save()`](#method-save)
    - [Event methods](#event-methods)
        - [Method `save_pre($isNew)`](#method-save_preisnew)
        - [Method `save_post($isNew)`](#method-save_postisnew)
        - [Method `delete_pre()`](#method-delete_pre)
        - [Method `delete_post()`](#method-delete_post)
- [Class `Query`](#class-query)
    - [Static methods](#static-methods-1)
        - [Method `wpdb()`](#method-wpdb-1)
    - [Instance methods](#instance-methods-1)
        - [Method `select([$...])`](#method-select)
        - [Method `delete()`](#method-delete)
        - [Method `update([$column [, $value]])`](#method-updatecolumn--value)
        - [Method `set($column [, $value])`](#method-setcolumn--value)
        - [Method `insert($data)`](#method-insertdata)
        - [Method `where($column [, $type_or_value [, $value]])`](#method-wherecolumn--type_or_value--value)
        - [Method `and_where($column [, $type_or_value [, $value]])`](#method-and_wherecolumn--type_or_value--value)
        - [Method `or_where($column [, $type_or_value [, $value]])`](#method-or_wherecolumn--type_or_value--value)
        - [Method `group_by($column [, $order])`](#method-group_bycolumn--order)
        - [Method `having($column [, $type_or_value [, $value]])`](#method-havingcolumn--type_or_value--value)
        - [Method `and_having($column [, $type_or_value [, $value]])`](#method-and_havingcolumn--type_or_value--value)
        - [Method `or_having($column [, $type_or_value [, $value]])`](#method-or_havingcolumn--type_or_value--value)
        - [Method `order_by($column [, $order])`](#method-order_bycolumn--order)
        - [Method `limit($limit)`](#method-limitlimit)
        - [Method `offset($offset)`](#method-offsetoffset)
        - [Method `join($table, $attribute, $foreign_attribute [, $type])`](#method-jointable-attribute-foreign_attribute--type)
        - [Method `sql()`](#method-sql)
        - [Method `get_results()`](#method-get_results)
        - [Method `get_row()`](#method-get_row)
        - [Method `get_col()`](#method-get_col)
        - [Method `get_var()`](#method-get_var)
        - [Method `get()`](#method-get)
        - [Method `get_one()`](#method-get_one)
        - [Method `execute()`](#method-execute)

### Class `ActiveRecord`

[](#class-activerecord)

#### Static Properties

[](#static-properties)

##### Property `$casts`

[](#property-casts)

Cast row values to native types.

###### Example:

[](#example)

```
class Slideshow extends \wp_activerecord\ActiveRecord {
    protected static $casts = [
        'num_slides' => 'int',
        'duration' => 'float',
        'active' => 'boolean',
        'created_at' => 'datetime',
    ];
}
```

#### Static Methods

[](#static-methods)

##### Method `create([$attributes])`

[](#method-createattributes)

Create a model with an array of attributes

###### Example:

[](#example-1)

```
$activeRecord = Table::create();
// or
$activeRecord = Table::create([
   'name'  => 'wp-activerecord',
   'title' => 'WordPress ActiveRecord'
]);
```

##### Method `delete_by_id($id)`

[](#method-delete_by_idid)

Delete a row by id

###### Example:

[](#example-2)

```
Table::delete_by_id(3);
```

##### Method `get([$id])`

[](#method-getid)

Get all model instances or a model instance by id

###### Example:

[](#example-3)

```
$activeRecords = Table::get(); // all records
$activeRecord = Table::get(3); // one record by id
```

##### Method `get_{type}_by_{column}($value [, $...])`

[](#method-get_type_by_columnvalue--)

Dynmamic finder method: Get a var, rows, results or model instances

###### Example:

[](#example-4)

```
$activeRecord = Table::get_one_by_title('WordPress');
$array = Table::get_by_name_or_title('wp-activerecord', 'WP');
$row = Table::get_row_by_name_and_title('wp', 'WP');
$var = Table::get_var_name_by_id(3);
```

##### Method `get_table_name()`

[](#method-get_table_name)

Get the table name

###### Example:

[](#example-5)

```
$table_name = Table::get_table_name();
```

##### Method `insert($data)`

[](#method-insertdata)

Insert one or multiple rows into the database

###### Example:

[](#example-6)

```
$last_insert_id = Table::insert([
   'name'  => 'wp-activerecord',
   'title' => 'WordPress ActiveRecord'
]);
// or
$last_insert_id = Table::insert([[
   'name'  => 'ActiveRecord',
   'title' => 'Class ActiveRecord'
], [
   'name'  => 'Query',
   'title' => 'Class Query'
]]);
```

##### Method `query()`

[](#method-query)

Get a query instance

###### Example:

[](#example-7)

```
$query = Table::query();
```

##### Method `update($column [, $value])`

[](#method-updatecolumn--value)

Shortcut method for creating a query instance and calling update on it

###### Example:

[](#example-8)

```
$query = Table::update('name', 'wp-activerecord-updated');
// or
$query = Table::update([
   'name'  => 'wp-activerecord-updated',
   'title' => 'Updated WordPress ActiveRecord'
]);
```

##### Method `wpdb()`

[](#method-wpdb)

Get the wpdb instance

###### Example:

[](#example-9)

```
$wpdb = Table::wpdb();

// use case:
$userInput = '20%';
Table::query()
  ->delete()
  ->where('name', 'like', '%' . Table::wpdb()->esc_like($userInput) . '%')
  ->execute();
```

#### Instance methods

[](#instance-methods)

##### Method `delete()`

[](#method-delete)

Delete the model

###### Example:

[](#example-10)

```
$activeRecord->delete();
```

##### Method `save()`

[](#method-save)

Save the model

###### Example:

[](#example-11)

```
$activeRecord->save();
```

#### Event methods

[](#event-methods)

##### Method `save_pre($isNew)`

[](#method-save_preisnew)

Called before saving the model

###### Example:

[](#example-12)

```
// in your derived class:
protected function save_pre($isNew) {
    $this->new = $isNew ? 1 : 0;
}
```

##### Method `save_post($isNew)`

[](#method-save_postisnew)

Called after saving the model

###### Example:

[](#example-13)

```
// in your derived class:
protected function save_post($isNew) {
    // do something with $this
}
```

##### Method `delete_pre()`

[](#method-delete_pre)

Called before deleting the model

###### Example:

[](#example-14)

```
// in your derived class:
protected function delete_pre() {
    // do something with $this
}
```

##### Method `delete_post()`

[](#method-delete_post)

Called after deleting the model

###### Example:

[](#example-15)

```
// in your derived class:
protected function delete_post() {
    // do something with $this
}
```

### Class `Query`

[](#class-query)

#### Static Methods

[](#static-methods-1)

##### Method `wpdb()`

[](#method-wpdb-1)

Get the wpdb instance

###### Example:

[](#example-16)

```
$wpdb = Query::wpdb();
```

#### Instance Methods

[](#instance-methods-1)

Select rows

##### Method `select([$...])`

[](#method-select)

###### Example:

[](#example-17)

```
$activeRecord = Table::query()
  ->select('id', 'name')
  ->get();
```

##### Method `delete()`

[](#method-delete-1)

Delete rows

###### Example:

[](#example-18)

```
Table::query()
  ->delete()
  ->where('name', 'wp')
  ->execute();
```

##### Method `update([$column [, $value]])`

[](#method-updatecolumn--value-1)

Update rows (Alias for \\wp\_activerecord\\Query::set)

###### Example:

[](#example-19)

```
Table::query()
  ->update()
  ->set('name', 'wp')
  ->execute();
// or
Table::query()
  ->update('name', 'wp')
  ->execute();
// or
Table::query()
  ->update([
    'name'  => 'wp',
    'title' => 'WordPress'
  ])
  ->execute();
```

##### Method `set($column [, $value])`

[](#method-setcolumn--value)

Set columns, which should be updated

###### Example:

[](#example-20)

```
Table::query()
  ->set('name', 'wp')
  ->execute();
// or
Table::query()
  ->set([
    'name'  => 'wp',
    'title' => 'WordPress'
  ])
  ->execute();
```

##### Method `insert($data)`

[](#method-insertdata-1)

Insert rows

###### Example:

[](#example-21)

```
Table::query()
  ->insert([
    'name'  => 'wp',
    'title' => 'WordPress'
  ])
  ->execute();
// or
Table::query
  ->insert([[
    'name'  => 'ActiveRecord',
    'title' => 'Class ActiveRecord'
  ], [
    'name'  => 'Query',
    'title' => 'Class Query'
  ]])
  ->execute();
```

##### Method `where($column [, $type_or_value [, $value]])`

[](#method-wherecolumn--type_or_value--value)

Add a where condition

###### Example:

[](#example-22)

```
$activeRecords = Table::query()
  ->where('name', 'wp')
  ->where('title', 'LIKE', '%active%')
  ->where([
    'start' => 12,
    'end'   => 37
  ])
  ->where(['deleted_at', null]) // query for NULL value, produces  `deleted_at` IS NULL
  ->where('value', '>', ['RAND()']) // raw value wrapped in array
  ->where('numbers', 'in', [[1, 2, 3]] // a array as raw value will be joined
  ->get();
```

##### Method `and_where($column [, $type_or_value [, $value]])`

[](#method-and_wherecolumn--type_or_value--value)

Alias for `where`.

##### Method `or_where($column [, $type_or_value [, $value]])`

[](#method-or_wherecolumn--type_or_value--value)

Alias for `where`, but adds a new group to the where clause, which will be added with the keyword OR

##### Method `group_by($column [, $order])`

[](#method-group_bycolumn--order)

Add a group by section

###### Example:

[](#example-23)

```
$activeRecords = Table::query()
  ->group_by('name', 'asc')
  ->get();
```

##### Method `having($column [, $type_or_value [, $value]])`

[](#method-havingcolumn--type_or_value--value)

Add a having condition

###### Example:

[](#example-24)

```
$activeRecords = Table::query()
  ->group_by('name')
  ->having(["SUM(price)"], ">", 10) // raw column value wrapped in array
  ->get();
```

##### Method `and_having($column [, $type_or_value [, $value]])`

[](#method-and_havingcolumn--type_or_value--value)

Alias for `having`.

##### Method `or_having($column [, $type_or_value [, $value]])`

[](#method-or_havingcolumn--type_or_value--value)

Alias for `having`, but adds a new group to the having clause, which will be added with the keyword OR

##### Method `order_by($column [, $order])`

[](#method-order_bycolumn--order)

Add a order by section

###### Example:

[](#example-25)

```
$activeRecords = Table::query()
  ->order_by('description')
  ->order_by('name', 'desc')
  ->get();
```

##### Method `limit($limit)`

[](#method-limitlimit)

Add a limit

###### Example:

[](#example-26)

```
$activeRecords = Table::query()
  ->limit(5)
  ->get();
```

##### Method `offset($offset)`

[](#method-offsetoffset)

Add a offset

###### Example:

[](#example-27)

```
$activeRecords = Table::query()
  ->offset(10)
  ->get();
```

##### Method `join($table, $attribute, $foreign_attribute [, $type])`

[](#method-jointable-attribute-foreign_attribute--type)

Add a join condition

###### Example:

[](#example-28)

```
$activeRecords = Table::query()
  ->join('OtherTable', 'id', 'table_id')
  ->get();
```

##### Method `sql()`

[](#method-sql)

Create the final sql statement

###### Example:

[](#example-29)

```
$sql = Table::query()
  ->select('description')
  ->where('description', 'like', 'Title: %')
  ->sql();
```

##### Method `get_results()`

[](#method-get_results)

Get the results of the query

###### Example:

[](#example-30)

```
$results = Table::query()
  ->get_results();
```

##### Method `get_row()`

[](#method-get_row)

Get the row of the query

###### Example:

[](#example-31)

```
$row = Table::query()
  ->where('name', 'this is a unique name')
  ->get_row();
```

##### Method `get_col()`

[](#method-get_col)

Get the column of the query

###### Example:

[](#example-32)

```
$descriptions = Table::query()
  ->select('description')
  ->get_col();
```

##### Method `get_var()`

[](#method-get_var)

Get the value of the query

###### Example:

[](#example-33)

```
$description = Table::query()
  ->select('description')
  ->where('name', 'this is a unique name')
  ->get_var();
```

##### Method `get()`

[](#method-get)

Get the results of the query as an array of model instances

###### Example:

[](#example-34)

```
$activeRecords = Table::query()
  ->get();
```

##### Method `get_one()`

[](#method-get_one)

Get the results of the query as a model instances

###### Example:

[](#example-35)

```
$activeRecord = Table::query()
  ->where('name', 'this is a unique name')
  ->get_one();
```

##### Method `execute()`

[](#method-execute)

Execute the query

###### Example:

[](#example-36)

```
Table::query()
  ->delete()
  ->where('name', 'this is a unique name')
  ->execute();
```

License
-------

[](#license)

This code is licensed under the MIT license.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 90.2% 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 ~155 days

Recently: every ~232 days

Total

7

Last Release

1962d ago

PHP version history (2 changes)v1.0.0PHP &gt;=5.3.0

v1.0.2PHP &gt;=5.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/00ac8f36d981c1499ba786b7ca344489a89451cf8ffc60a29b228bba0525e354?d=identicon)[friedolinfoerder](/maintainers/friedolinfoerder)

---

Top Contributors

[![friedolinfoerder](https://avatars.githubusercontent.com/u/2007941?v=4)](https://github.com/friedolinfoerder "friedolinfoerder (46 commits)")[![roberto-ayala](https://avatars.githubusercontent.com/u/1773587?v=4)](https://github.com/roberto-ayala "roberto-ayala (3 commits)")[![euperia](https://avatars.githubusercontent.com/u/2648745?v=4)](https://github.com/euperia "euperia (1 commits)")[![impudentem](https://avatars.githubusercontent.com/u/8874551?v=4)](https://github.com/impudentem "impudentem (1 commits)")

---

Tags

activerecorddatabasephpsqlwordpressphpwordpressdatabasesqlactiverecord

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/friedolinfoerder-wp-activerecord/health.svg)

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

###  Alternatives

[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)[druidfi/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

35489.8k6](/packages/druidfi-mysqldump-php)[butschster/dbml-parser

DBML (database markup language) parser written on PHP8.

6416.8k2](/packages/butschster-dbml-parser)[calebdw/laravel-sql-entities

Manage SQL entities in Laravel with ease.

301.3k](/packages/calebdw-laravel-sql-entities)

PHPackages © 2026

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