Copy content stored in meta to post content
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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Here’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 );
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0