Created
November 25, 2020 13:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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