Search by

messageagency / ma-migrate

messageagency

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

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

0.1.0 2026-11-03 18:39 UTC

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

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
idUnique id. Defaults to the file name: migration-example-news.php is example_news (hyphens stand for underscores).
labelShown by status.
migration_groupThe group the migration belongs to.
migration_tagsTags, for --tag.
sourceThe source plugin and its configuration.
processDestination property => pipeline.
destinationThe destination plugin and its configuration.
migration_dependenciesrequired (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_empty with method: 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
jsonpath (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.
csvpath, header_offset (default 0; null for no header), column_names, delimiter, enclosure, escape, trim. Strips Excel's byte order mark.
embedded_datadata_rows: the rows themselves.
sqlquery ({prefix} becomes the table prefix), database, batch_size.
wp_postsAnother 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_termsAnother 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

PluginDoesConfiguration
getRead a value, or a list of themsource
default_valueA default for an empty value (or a fixed value)default_value, strict
static_mapMap through a tablemap, default_value, bypass, ignore_case
explodeSplit a stringdelimiter, limit, trim
concatJoin a listdelimiter
callbackCall a function or closurecallable, unpack_source, handle_multiples
extractOne value from an arrayindex, default
flattenFlatten nested lists
filter_emptyDrop empty elements
uniqueDrop repeated elements
null_coalesceFirst value that is not nulldefault_value
sub_processA process section per element, building a list of arrays (repeaters)process
skip_on_emptyStop on an empty valuemethod, message
skip_on_valueStop on given valuesvalue, not_equals, method, message
skip_row_if_not_setSkip the row when a key is missingindex, message
str_replaceReplace textsearch, replace, regex, ignore_case
substrPart of a stringstart, length
format_dateReformat a datefrom_format, to_format, from_timezone, to_timezone
logSave the value as a message
migration_lookupThe id an item got in another migrationmigration, no_stub, missing_message
post_lookupAn existing post by title, slug, ID or metapost_type, by, ignore_case, missing_message
term_lookupAn existing termtaxonomy, by, missing_message
term_generateA term, created when missingtaxonomy
attachment_lookupA media item by its file path or URLmissing_message
file_copyCopy or download a file into uploadsbase, destination, file_exists, missing_message
html_cleanTidy old body HTMLstrip_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).

PluginProperties
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.
attachmentEverything 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>.
userID (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 override count(), fields() and prepare_row() (return false to leave a row out).
  • A process plugin implements transform(). Override handles_multiples() to receive lists whole. Save messages with $executable->save_message(); stop with MA_Migrate_Skip_Process_Exception, skip with MA_Migrate_Skip_Row_Exception, fail with MA_Migrate_Exception.
  • A destination implements import(), rollback(), exists() and fields(), and optionally supports_stubs(), stub() and find_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_importAround an import.
ma_migrate_pre_row_save, ma_migrate_post_row_saveAround each saved row.
ma_migrate_pre_rollback, ma_migrate_post_rollbackAround 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.