I'm working on a site that had an existing theme that used meta fields to store blocks (bad practice IMO but pre-block editor).
The problem is there are over 300 posts and all the different "blocks" are stored in what looks like repeated meta fields (i.e. flexible_content_1_content, flexible_content_2_content, etc). Does anyone know of a way to copy metadata content into the post content using WP CLI or custom code? Bonus points if I can copy the metadata to separate blocks in the block editor.
I'm working on a site that had an existing theme that used meta fields to store blocks (bad practice IMO but pre-block editor).
The problem is there are over 300 posts and all the different "blocks" are stored in what looks like repeated meta fields (i.e. flexible_content_1_content, flexible_content_2_content, etc). Does anyone know of a way to copy metadata content into the post content using WP CLI or custom code? Bonus points if I can copy the metadata to separate blocks in the block editor.
Share Improve this question asked Aug 11, 2020 at 17:26 themattygthemattyg 133 bronze badges 1- Write a WP CLI script to run through the posts and copy over the meta values into post content? Doesn't seem complicated. – vancoder Commented Aug 11, 2020 at 17:46
1 Answer
Reset to default 0Here's an example of how to get the meta and set it as the post content. You would need to add all the meta keys to the $meta_fields
array.
Obviously test this locally before running in production because it will overwrite whatever is currently in the post content.
function migrate_post_data() {
// Add all the meta keys you want to migrate to this array.
$meta_fields = array(
'flexible_content_1_content',
'flexible_content_2_content'
);
// Get all the posts.
$args = array(
'post_type' => 'post', // You may need to change this.
'posts_per_page' => 400,
);
$posts = get_posts( $args );
// Loop over each post.
foreach ( $posts as $post ) {
$meta_field_content = array();
// Loop over each meta field and get their content, adding it to an array.
foreach( $meta_fields as $meta_field ) {
$content = get_post_meta( $post->ID, $meta_field, true );
if ( ! empty( trim( $content ) ) ) {
$meta_field_content[] = $content;
}
}
if ( empty( $meta_field_content ) ) {
continue;
}
// Set the the post content as whatever the meta fields were.
$post_args = array(
'ID' => $post->ID,
'post_content' => implode( ' ', $meta_field_content ),
);
wp_update_post( $post_args );
}
}