Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created November 25, 2020 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanknudtskov/4bbab89d7e43f5be2c20eedc889c616e to your computer and use it in GitHub Desktop.
Save yanknudtskov/4bbab89d7e43f5be2c20eedc889c616e to your computer and use it in GitHub Desktop.
Example code to migrate from ACF label based index of choice fields to a value : label based index
<?php
add_shortcode( 'migrate_acf_choice_data', 'migrate_acf_choice_data' );
function migrate_acf_choice_data() {
global $wpdb;
$meta_key_to_migrate = ''; // Set the name of the acf_field to migrate the data for
$dry_run = true; // Set to false to enable live run
$html = '';
$sql = "SELECT post_id, meta_value FROM {$wpdb->prefix}postmeta where meta_key = '{$meta_key_to_migrate}' and meta_value != ''";
$postmetas = $wpdb->get_results( $sql );
foreach( $postmetas as $postmeta ) {
$unserialized_data = unserialize( $postmeta->meta_value );
$new_data = array();
foreach( $unserialized_data as $key => $data ) {
if( $data == 'INSERT LABEL_1 TO SEARCH FOR HERE' ) {
$new_data[] = '0'; // Change to corresponding value of the update ACF choice field
}
if( $data == 'INSERT LABEL_2 TO SEARCH FOR HERE' ) {
$new_data[] = '1'; // Change to corresponding value of the update ACF choice field
}
}
if( !empty( $new_data ) ) {
$new_data_serialized = serialize( $new_data );
if( $dry_run == false ) {
$sql_update = "UPDATE {$wpdb->prefix}postmeta SET meta_value = '{$new_data_serialized}' WHERE meta_key = '{$meta_key_to_migrate}' AND post_id = '{$postmeta->post_id}';";
$wpdb->query( $sql_update );
} else {
$html .= $sql_update;
$html .= '<br>';
}
}
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment