WordPress Importer: allow updating metadata
Published: – Leave a comment Last update:
By default, the WordPress importer detects existing data and doesn’t allow updating them. But what if you explicitly want to update existing data – especially metadata?
The WordPress importer checks whether a post exists, and allows you to manipulate that via the filter wp_import_existing_post. However, it doesn’t allow the same for metadata, since metadata won’t be checked. In fact, the WordPress importer just uses add_post_meta to add metadata to a post. And since add_post_meta does not update existing metadata, but only adding data if there is no data yet, it won’t update anything.
The solution is relatively simple: before adding the metadata, delete any existing metadata. As mentioned, there is no filter or any hook for metadata whatsoever in the importer. So we just use the mentioned wp_import_existing_post filter to delete the metadata before adding our metadata.
/**
* Update existing postmeta data.
*
* @param int $post_id post ID
* @return int Post ID
*/
public function update_existing_postmeta( int $post_id ): int {
if ( $post_id > 0 ) {
// delete post metadata to allow its "update"
// the importer uses add_post_meta, which does not update itself
$metadata = \get_post_meta( $post_id );
foreach ( \array_keys( $metadata ) as $meta_key ) {
\delete_post_meta( $post_id, $meta_key );
}
}
return $post_id;
}
\add_filter( 'wp_import_existing_post', 'update_existing_postmeta' );
Code language: PHP (php)
Likes