wp-cli error: “Term is missing a parent”

I recently tried to export the posts from a large WP site I inherited and faced the same issue.

For some reason, there were terms (referenced via term_id) linked to other “parent” terms inside the “wp_term_taxonomy” table and these “parent” terms simply did not exist in the “wp_terms” table.

So the simplest solution is to just set the parent to 0 for these terms inside the “wp_term_taxonomy” table.

BEFORE PROCEEDING ensure you’ve taken a backup of your database. I can’t stress this enough…

Then identify the offending terms that have a “parent” term which does not exist:

/* For categories */
SELECT * FROM `wp_term_taxonomy` WHERE taxonomy = 'category' AND parent NOT IN(SELECT term_id FROM `wp_terms`);

/* For tags */
SELECT * FROM `wp_term_taxonomy` WHERE taxonomy = 'post_tag' AND parent NOT IN(SELECT term_id FROM `wp_terms`);

/* For custom terms */
SELECT * FROM `wp_term_taxonomy` WHERE taxonomy = 'some_custom_term' AND parent NOT IN(SELECT term_id FROM `wp_terms`);

And finally update the “wp_term_taxonomy” table accordingly and set “parent” to 0:

/* For categories */
UPDATE `wp_term_taxonomy` SET parent = 0 WHERE taxonomy = 'category' AND parent NOT IN(SELECT term_id FROM `wp_terms`);

/* For tags (we basically "flatten" all of them to a single level) */
UPDATE `wp_term_taxonomy` SET parent = 0 WHERE taxonomy = 'post_tag';

/* For custom terms */
UPDATE `wp_term_taxonomy` SET parent = 0 WHERE taxonomy = 'some_custom_term' AND parent NOT IN(SELECT term_id FROM `wp_terms`);

After that, running your wp export... command will just work.

P.S. If you use a DB table prefix other than “wp_”, you obviously need to update all the SQL queries above accordingly.