baxtian / wp_importer
Class to be inherite to create importers
Requires
- php: >=7.4
- baxtian/php-singleton: ^0.6.6
- phpoffice/phpspreadsheet: ^1.24
- psr/simple-cache: ^1
Requires (Dev)
- brain/monkey: ^2.6
- php-mock/php-mock: ^2.3
- phpunit/phpunit: ^9.5
- timber/timber: ^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-master
- 0.3.54
- 0.3.53
- 0.3.52
- 0.3.51
- 0.3.50
- 0.3.49
- 0.3.48
- 0.3.47
- 0.3.46
- 0.3.45
- 0.3.44
- 0.3.43
- 0.3.42
- 0.3.41
- 0.3.40
- 0.3.39
- 0.3.38
- 0.3.37
- 0.3.36
- 0.3.35
- 0.3.34
- 0.3.33
- 0.3.32
- 0.3.31
- 0.3.30
- 0.3.29
- 0.3.28
- 0.3.27
- 0.3.26
- 0.3.25
- 0.3.24
- 0.3.23
- 0.3.22
- 0.3.21
- 0.3.20
- 0.3.19
- 0.3.18
- 0.3.17
- 0.3.16
- 0.3.15
- 0.3.14
- 0.3.13
- 0.3.12
- 0.3.11
- 0.3.10
- 0.3.9
- 0.3.8
- 0.3.7
- 0.3.6
- 0.3.5
- 0.3.4
- 0.3.3
- 0.3.2
- 0.3.1
- 0.3.0
- 0.1.14
- 0.1.13
- 0.1.12
- 0.1.11
- 0.1.10
- 0.1.9
- 0.1.8
- 0.1.7
- 0.1.6
- 0.1.5
- 0.1.4
- 0.1.3
- 0.1.2
- 0.1.1
- 0.1.0
- dev-laminas-di
This package is auto-updated.
Last update: 2026-10-29 03:09:23 UTC
README
Base class for creating WordPress importers/exporters (CSV + XLSX). Appears under Tools → Import in the WordPress admin.
Usage
class MyImporter extends \Baxtian\WP_Importer
{
use \Baxtian\SingletonTrait;
protected function __construct()
{
$this->tipo = 'product'; // singular slug
$this->tipos = 'products'; // plural slug
$this->accion = 'import_products';// importer action slug
add_action('init', [$this, 'init']);
parent::__construct();
}
public function init(): void
{
$this->campos = [...]; // define here — translations are loaded
$this->textos = [
'import_button' => __('Import Products', 'domain'),
'import_file' => __('Products file', 'domain'),
'plural' => __('products', 'domain'),
'description' => __('Import products from CSV or XLSX.', 'domain'),
'mensaje_publicacion' => __('Created: %d, Updated: %d, Linked: %d', 'domain'),
// ↑ Use commas as separators — JS splits by "," to build a bullet list
];
// For custom DB tables, hook import/export here:
add_filter('MrkImporter/import_data', [$this, 'handle_import'], 10, 4);
add_filter('MrkImporter/export_data', [$this, 'handle_export'], 10, 4);
parent::init();
}
}
Important: define
$camposand$textosinsideinit(), not the constructor — translations must be loaded first. Callparent::init()at the end ofinit().
Campo types
| type | description |
|---|---|
id | Post ID — used for matching on import |
field | post_title or any direct post field |
thumbnail | Featured image (URL on export, URL/path on import) |
term | Taxonomy term (comma-separated on export) |
postmeta | Generic postmeta value |
postmeta_bool | Boolean postmeta — exports as 1/0 |
postmeta_textarea | Multiline postmeta |
postmeta_date | Date postmeta (Y-m-d) |
postmeta_datetime | Datetime postmeta (Y-m-d H:i:s) |
p2p | Post-to-post relationship — requires 'p2p' key |
ignore | Header/export mapping only — no-op on import |
Column headers
The file header is the key the importer matches each column by (rename_columns()), so it must not change between exporting and importing.
- Default: a campo without
titleuses itsnameas the header (post_title,_barcode,provider). That is enough when the people who fill the file know these names. title: add one only when the people who fill the file need friendlier names, and write it as a variable name in their language: lowercase,_between words, no spaces or accents ('title' => 'precio_compra').- Never translate it (no
__()): in wp-admin translations follow each user's language, and a translation fix or a missing.mowould change the header. A file exported by one user, or before a translation update, or on a site in another language, would be rejected. Thetextosare translated; the headers are identifiers. - Columns built from the site's data (one per warehouse, per attribute…):
prefix:variable, with a fixed prefix and the variable part taken from a stable value such as a slug (cantidad:bodega_centro,atributo:talla). The importer recognises the family by the prefix, and two families cannot produce the same header. Columns that are not incamposare recognised withMrkImporter/column_name.
ignore
Declares a field that participates in rename_columns() (so the file header uses its title, see Column headers) and in export, but is never written by the built-in import switch — it's a no-op on import.
Use it when a column's real value must be set through business logic that can't go through a raw update_post_meta() — for example, a value that has to pass through a domain object, trigger side effects, or be resolved by a third-party listener. Hook into MrkImporter/row_added (fired after all other fields of the row are processed) to write the value yourself:
$this->campos = [
['name' => 'id', 'type' => 'id'],
['name' => 'post_title', 'type' => 'field'],
['name' => 'price', 'type' => 'ignore', 'title' => 'precio'],
];
add_action('MrkImporter/row_added', function ($post_id, $tipo, $line) {
if ($tipo === 'product') {
MyPricingService::set_price($post_id, $line['price']);
}
}, 10, 3);
Hooks
| Hook | Type | Args | When |
|---|---|---|---|
MrkImporter/import_data | filter | (false, $tipo, $data, $campos, $structureImporter, $step) | Before importing — return ['nuevas'=>int, 'modificadas'=>int, 'terminos_nuevos'=>int] to replace built-in import; return false to fall through |
MrkImporter/validate | filter | ([], $tipo, $filas, $campos) | Step 1, before writing anything — return the list of problems found in the whole file; with any problem nothing is written |
MrkImporter/column_name | filter | (null, $column, $tipo, $direction, $campos) | When a header is not in campos — return the field name that corresponds, or null |
MrkImporter/avisos | filter | ($avisos, $tipo, $step) | After each step — return the notices to show apart from the errors |
MrkImporter/export_data | filter | ($data, $tipo, $tipos, $campos) | Before writing the export file — return numeric array of rows (row 0 = header of campo names) |
MrkImporter/row_added | action | ($post_id, $tipo, $line) | After each imported row (built-in importer only) |
MrkImporter/attach_image | action | ($attach_id, $attach_data) | After each image is uploaded and processed |
MrkImporter/upload_failed | action | ($uri) | When a media URL could not be downloaded; the URL is skipped and no attachment is created |
Rejected files and validation
- A header that is not in
campos(and thatMrkImporter/column_namedoes not recognise) rejects the whole file before anything is written, naming the columns. - A row whose ID does not exist, or whose title matches several published items, is skipped and reported with its row number; an empty ID matches by title.
MrkImporter/validatereceives the rows with the file row number as key (the header is row 1) and the field names as keys of each row:
add_filter('MrkImporter/validate', function ($errors, $tipo, $filas, $campos) {
if ($tipo !== 'product') {
return $errors;
}
foreach ($filas as $n => $fila) {
if (!empty($fila['price']) && !is_numeric($fila['price'])) {
$errors[] = sprintf('Row %d: invalid price "%s"', $n, $fila['price']);
}
}
return $errors;
}, 10, 4);
- Only one import of the same type runs at a time; a second one stops with a message and writes nothing.
Export format
handle_export must return a numeric array where row 0 is the header (campo name values) and rows 1…N are data rows (numeric arrays aligned with the header). rename_columns() translates names → titles for the downloaded file.
$rows = [['name', 'email', 'webinars']]; // header
$rows[] = ['John', 'john@example.com', 'Webinar 1'];
return $rows;
XLSX date cells
Cells formatted as dates in Excel are automatically converted to Y-m-d H:i:s strings. No manual serial-number handling needed in the importer.
Access control
WordPress restricts Tools → Import to users with the import capability. Grant it explicitly for custom roles:
add_role('my_role', 'My Role', ['read' => true, 'import' => true]);
Maintainers
Juan Sebastián Echeverry baxtian.echeverry@gmail.com
Changelog
See CHANGELOG.md.