messageagency / ma-migrate
Repeatable content migrations for WordPress, run from WP-CLI: sources, process pipelines, destinations, an id map and rollback.
Package info
bitbucket.org/messageagency/ma-migrate
Type:wordpress-plugin
pkg:composer/messageagency/ma-migrate
Requires
- php: >=8.2
- composer/installers: ^1.0 || ^2.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-12-04 05:14:13 UTC
README
Repeatable content migrations for WordPress, run from WP-CLI. A migration is a PHP array that says where items come from (a source), how each field is built (process pipelines) and what they become (a destination). MA Migrate records every item it imports in an id map, so a migration can be run again and again: it updates what it made before, picks up rows that changed, references items from other migrations by their old ids, and can be rolled back.
Nothing runs on a page request. Everything is wp migrate ....
- Install
- A first migration
- Concepts
- Commands
- Sources
- Process plugins
- Destinations
- Writing plugins
- Hooks
- Recipes
Install
Add the repository and require the package in the site's composer.json:
"repositories": [
{ "type": "vcs", "url": "git@bitbucket.org:messageagency/ma-migrate.git" }
],
"require": {
"messageagency/ma-migrate": "^0.1"
}
Activate it (wp plugin activate ma-migrate). It needs PHP 8.2 and WordPress 6.9.
The migrations themselves live in a small site plugin (for example example-migrate), which declares Requires Plugins: ma-migrate and registers its directory of definitions:
add_action( 'ma_migrate_register', function ( MA_Migrate_Registry $registry ) {
$registry->add_directory( __DIR__ . '/migrations' );
} );
Site migration plugins usually live on a branch of their own and are removed after launch; MA Migrate itself can stay installed.
A first migration
migrations/migration-example-news.php:
<?php
return [
'label' => 'News',
'migration_group' => 'example',
'source' => [
'plugin' => 'json',
'path' => WP_CONTENT_DIR . '/uploads/private/export/posts.json',
'item_selector' => 'items',
'ids' => [ 'id' => [ 'type' => 'integer' ] ],
],
'process' => [
'post_title' => 'title',
'post_name' => 'slug',
'post_date' => 'date',
'post_status' => [ 'plugin' => 'default_value', 'default_value' => 'publish' ],
'post_content' => [
[ 'plugin' => 'get', 'source' => 'body' ],
[ 'plugin' => 'html_clean', 'strip_block_comments' => true, 'root_relative_hosts' => [ 'old.example.org' ] ],
],
'thumbnail' => [
[ 'plugin' => 'migration_lookup', 'source' => 'image_id', 'migration' => 'example_media', 'no_stub' => true ],
[ 'plugin' => 'skip_on_empty', 'method' => 'process' ],
],
'terms/category' => [
[ 'plugin' => 'explode', 'source' => 'topics', 'delimiter' => ',', 'trim' => true ],
[ 'plugin' => 'term_generate', 'taxonomy' => 'category' ],
],
'acf/field_abc123' => 'subtitle',
'meta/_old_id' => 'id',
],
'destination' => [ 'plugin' => 'post:post' ],
'migration_dependencies' => [ 'required' => [ 'example_media' ] ],
];
wp migrate status --group=example
wp migrate import --group=example
wp migrate messages example_news
Concepts
Definitions
| Key | |
|---|---|
id | Unique id. Defaults to the file name: migration-example-news.php is example_news (hyphens stand for underscores). |
label | Shown by status. |
migration_group | The group the migration belongs to. |
migration_tags | Tags, for --tag. |
source | The source plugin and its configuration. |
process | Destination property => pipeline. |
destination | The destination plugin and its configuration. |
migration_dependencies | required (must be complete before this runs) and optional (run first when run together). |
Definitions are PHP, so they can call functions, share pipelines through helper functions and use closures (with the callback plugin) for one-off rules.
Groups
group-<id>.php returns a group: label, description and shared_configuration, which is merged under every migration in the group. Put the export path, track_changes or anything else the migrations share there:
return [
'label' => 'Example',
'shared_configuration' => [
'source' => [ 'track_changes' => true ],
],
];
Rows
A source yields one array per item. Process pipelines read it by name, or by / path into nested arrays (meta/video, review/issue_areas). Each pipeline's result is set on the row as a destination property; a later pipeline reads one back with @ (@thumbnail). Destination properties whose names start with _ are working values: other pipelines can read them, but they are never saved.
constants in the source configuration appear as constants/<name>.
Pipelines
A pipeline is a list of steps. The shorthand 'post_title' => 'title' is a one-step get. A step with a source reads that value first; every other step takes the previous step's value.
When a value is a list, each step that does not handle lists itself (explode does not, concat does) is applied to every element in turn. So explode then term_lookup then filter_empty turns "A, B, C" into a list of term ids.
A step can:
- stop the pipeline (
skip_on_emptywithmethod: process): the property is left unset, so an update keeps the existing value; - skip the row (
method: row): the row is recorded as ignored, with an optional message; - fail the row (throw
MA_Migrate_Exception): the row is recorded as failed and the message saved.
The id map
Two tables, {prefix}ma_migrate_map and {prefix}ma_migrate_message, keyed by migration id. Each source row has one map record: the destination id it became, its status (imported, needs update, ignored, failed), what rollback should do with it, and a hash of the source row.
On import a row is processed when it is new, marked for update (--update), changed (with track_changes on the source), failed before (with track_changes), or above the high water mark. Everything else is counted as unchanged and not touched, so hand edits survive re-runs until the source row changes.
References between migrations
migration_lookup turns an old id into the id the item got in another migration. When the other item has not been imported yet, it makes a stub (a draft placeholder) and records it as needing an update, so the other migration fills it in when it runs. Pass no_stub: true where a missing reference should stay empty instead. Attachments are never stubbed.
Adopting existing content
Setting a destination's id property (ID for posts and users, term_id for terms) to an existing item, usually with post_lookup, makes the row update that item instead of creating one. Adopted items are kept on rollback. overwrite_properties limits what an update writes; an empty list leaves existing items untouched.
wp migrate adopt --meta-key=<key> takes over content an earlier import made (outside MA Migrate) that stored the old id in a meta key. Those items become the migration's own: the next import rewrites them in place, and rollback deletes them.
Rollback
wp migrate rollback deletes what a migration created, in reverse dependency order, and forgets its rows. Items it adopted, and every item of a destination configured with rollback_action: preserve, are kept. Attachments lose their records but keep their files unless the destination sets delete_files.
Commands
| Command | |
|---|---|
wp migrate status [<id>...] [--group] [--tag] [--format] | Totals, imported, needing update, ignored, failed, unprocessed, messages, last run. |
wp migrate import [<id>...] [--all] [--group] [--tag] | Import. --update processes imported rows again; --limit=<n>; --idlist=<ids> (comma-separated, composite parts joined with :); --execute-dependencies; --force ignores unfinished dependencies; --sync rolls back items whose source rows have gone; --feedback=<n> prints progress; --continue-on-failure. |
wp migrate rollback [<id>...] [--all] [--group] [--tag] [--idlist] [--yes] | Roll back. |
wp migrate adopt [<id>...] --meta-key=<key> | Take over content an earlier import made. |
wp migrate messages <id> | The messages saved during the last runs. |
wp migrate fields <id> | Source fields and destination properties. |
wp migrate stop <id> | Stop a running import after its current row. |
wp migrate reset-status <id> | Set a migration back to idle after a run that died. |
Sources
Every source takes ids (required: [ name => [ 'type' => 'integer'|'string' ] ]), fields (name => label, for wp migrate fields), constants, track_changes and high_water_property (a property that only grows, such as a modified date: rows at or below the last run's highest value are skipped).
| Plugin | |
|---|---|
json | path (file or URL), item_selector (/ path to the list of items), fields as name => label, or a list of [ name, label, selector ] to build rows from selectors. |
csv | path, header_offset (default 0; null for no header), column_names, delimiter, enclosure, escape, trim. Strips Excel's byte order mark. |
embedded_data | data_rows: the rows themselves. |
sql | query ({prefix} becomes the table prefix), database, batch_size. |
wp_posts | Another WordPress site's posts, straight from its tables: post_type, post_status, meta (true, a list of keys, or false), terms, database. Rows get meta, terms, thumbnail, and file, metadata and alt for attachments. Ids default to ID. |
wp_terms | Another WordPress site's terms: taxonomy, meta, database. Parents come first. |
database is left out for this site's own database, names an entry of the MA_MIGRATE_DATABASES constant, or gives name, user, password, host and prefix directly. Import a copy of the old site's database next to the new one and point the WordPress sources at it, and there is nothing to export:
// wp-config-local.php, or anywhere kept out of git.
define( 'MA_MIGRATE_DATABASES', [
'legacy' => [ 'name' => 'oldsite', 'user' => 'root', 'password' => '', 'host' => '127.0.0.1', 'prefix' => 'wp_' ],
] );
Process plugins
| Plugin | Does | Configuration |
|---|---|---|
get | Read a value, or a list of them | source |
default_value | A default for an empty value (or a fixed value) | default_value, strict |
static_map | Map through a table | map, default_value, bypass, ignore_case |
explode | Split a string | delimiter, limit, trim |
concat | Join a list | delimiter |
callback | Call a function or closure | callable, unpack_source, handle_multiples |
extract | One value from an array | index, default |
flatten | Flatten nested lists | |
filter_empty | Drop empty elements | |
unique | Drop repeated elements | |
null_coalesce | First value that is not null | default_value |
sub_process | A process section per element, building a list of arrays (repeaters) | process |
skip_on_empty | Stop on an empty value | method, message |
skip_on_value | Stop on given values | value, not_equals, method, message |
skip_row_if_not_set | Skip the row when a key is missing | index, message |
str_replace | Replace text | search, replace, regex, ignore_case |
substr | Part of a string | start, length |
format_date | Reformat a date | from_format, to_format, from_timezone, to_timezone |
log | Save the value as a message | |
migration_lookup | The id an item got in another migration | migration, no_stub, missing_message |
post_lookup | An existing post by title, slug, ID or meta | post_type, by, ignore_case, missing_message |
term_lookup | An existing term | taxonomy, by, missing_message |
term_generate | A term, created when missing | taxonomy |
attachment_lookup | A media item by its file path or URL | missing_message |
file_copy | Copy or download a file into uploads | base, destination, file_exists, missing_message |
html_clean | Tidy old body HTML | strip_block_comments, captions_to_figures, root_relative_hosts, strip_styles, strip_font_tags |
missing_message saves a warning against the row when a lookup finds nothing; {value} in it is the value looked for.
Destinations
Every destination takes overwrite_properties and rollback_action (see Adopting and Rollback).
| Plugin | Properties |
|---|---|
post:<type> | The wp_insert_post() columns, meta/<key>, acf/<field> (by key or name, through update_field()), terms/<taxonomy>, thumbnail. Option unfiltered_html saves content without WordPress's HTML filtering. |
attachment | Everything post takes, plus file (path under uploads), metadata, alt. Options generate_metadata, delete_files. |
term:<taxonomy> | term_id (adopt), name, slug, description, parent, meta/<key>, acf/<field>. |
user | ID (adopt), the wp_insert_user() fields, meta/<key>, acf/<field>. Option reassign. |
Unknown properties fail the row, so a typo shows up as a message instead of silently doing nothing.
Writing plugins
Extend MA_Migrate_Source, MA_Migrate_Process or MA_Migrate_Destination and register the class on ma_migrate_register:
class Example_Process_Initials extends MA_Migrate_Process {
public function transform( $value, MA_Migrate_Executable $executable, MA_Migrate_Row $row, $property ) {
return implode( '', array_map( fn( $word ) => $word[0], explode( ' ', (string) $value ) ) );
}
}
add_action( 'ma_migrate_register', function ( MA_Migrate_Registry $registry ) {
$registry->add_process_plugin( 'example_initials', 'Example_Process_Initials' );
} );
- A source implements
initialize_iterator(), yielding one array per item, and can overridecount(),fields()andprepare_row()(return false to leave a row out). - A process plugin implements
transform(). Overridehandles_multiples()to receive lists whole. Save messages with$executable->save_message(); stop withMA_Migrate_Skip_Process_Exception, skip withMA_Migrate_Skip_Row_Exception, fail withMA_Migrate_Exception. - A destination implements
import(),rollback(),exists()andfields(), and optionallysupports_stubs(),stub()andfind_by_meta().
A plugin registered with a core id replaces the core plugin.
Hooks
| Hook | |
|---|---|
ma_migrate_register (action) | Register directories, migrations, groups and plugins. |
ma_migrate_definitions (filter) | Alter definitions before they are built. |
ma_migrate_prepare_row (filter) | Return false to leave a row out; the row can be changed. |
ma_migrate_pre_import, ma_migrate_post_import | Around an import. |
ma_migrate_pre_row_save, ma_migrate_post_row_save | Around each saved row. |
ma_migrate_pre_rollback, ma_migrate_post_rollback | Around a rollback. |
Recipes
A review spreadsheet over an export. Write a source plugin that yields each exported item merged with its spreadsheet row (under a key such as review), turn on track_changes, and a corrected spreadsheet row is picked up on the next run without --update.
A WordPress site from a copy of its database. wp_posts with post_type: attachment into attachment (with file_copy from the old uploads URL for file), then wp_posts per post type, with migration_lookup on the media migration for thumbnail.
A hierarchy. wp_terms reads parents first; set parent with migration_lookup on the same migration.
Repeater rows. Build a list, then sub_process with the repeater's sub-field names: [ 'plugin' => 'sub_process', 'process' => [ 'file' => 'value' ] ].
Testing
tests/smoke.sh runs a small set of throwaway migrations through import, change tracking, stubs, adoption, skipped rows, messages and rollback against a local site. It creates and deletes a few pages; do not run it against a shared environment.