Help topics

Use Morphic models and entries in your plugin

Other plugins and themes on the same site can define models, and read and write entries, with PHP functions. The calls run inside WordPress. They make no HTTP request.

Before you start

  • Morphic is active on the site.
  • You can add PHP code to a plugin or a theme on that site.

Warning: The PHP functions do not check permissions. They save as the logged-in WordPress user, so your code decides who may read or change an entry. Check the user before you call morphic_update() or morphic_create().

Define a model in code

Register the model on the morphic/ready action. Morphic runs that action on WordPress init at priority 5.

add_action('morphic/ready', function () {
    morphic_define([
        'type' => 'ticket',
        'prefix' => 'tkt',
        'fields' => [
            'subject' => ['kind' => 'text', 'max' => 200, 'required' => true],
            'status' => ['kind' => 'enum', 'values' => ['open', 'closed'], 'default' => 'open', 'index' => true],
        ],
    ]);
});
  • The prefix is exactly three lowercase letters. The ids of its entries start with it.
  • Set 'index' => true on a field before you query by it. A query on a field with no index fails.
  • Calling morphic_define() again with the same definition changes nothing. Morphic returns the stored model.

Create, read and update an entry

$ticket = morphic_create('ticket', ['subject' => 'Printer is on fire']);
$open = morphic_query('ticket', ['status' => 'open'], ['limit' => 20]);
$ticket = morphic_update($ticket['id'], ['status' => 'closed'], $ticket['rev']);
echo esc_html(morphic_field($ticket, 'subject'));

Result: morphic_create() returns the new entry. morphic_query() returns the open tickets, up to 20. morphic_update() saves the change and returns the updated entry.

Pass the rev you read from the entry. If the entry has changed since then, the update fails with the code conflict.

Functions and methods

The global functions are morphic_define(), morphic_get(), morphic_query(), morphic_field(), morphic_create(), morphic_update() and morphic_setting(). Each one calls the method of the same name on the Morphic\Morphic class. The class also has many, list, by, search, delete, restore, link, unlink, related and transaction.

Handle errors and changes

  • Errors are thrown as Morphic\Failure. Its codes include conflict and invalid. Catch Morphic\Failure around the calls.
  • Listen to the morphic/written action when an entry is created, updated or restored. Listen to morphic/deleted when an entry is deleted.