Created
August 23, 2017 17:24
-
-
Save solepixel/cd555e15a7a85718205cad8a2ad64dfc to your computer and use it in GitHub Desktop.
This gist will provide legacy support for the instance when you need to convert an ACF field from a plain text field to a multi-select taxonomy field. It will convert existing values to the proper array format and pull in and convert original values to array. WARNING: It does not create new terms. This could be added pretty easily tho, however o…
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 | |
# create your taxonomy | |
# In this example, I'm using "landing-section-class" as the taxonomy | |
# Remove the unneeded meta box | |
add_action( 'admin_menu', '_briand_remove_landing_section_class_metabox' ); | |
function _briand_remove_landing_section_class_metabox() { | |
remove_meta_box( 'tagsdiv-landing-section-class', 'page', 'side' ); | |
} | |
# Handle load_value to convert values to arrays | |
# All my instances use the field name section_class, however each instance would need to be filtered | |
add_filter( 'acf/load_value/name=section_class', '_briand_section_class_legacy_support', 9, 3 ); | |
function _briand_section_class_legacy_support( $value, $post_id = NULL, $field = NULL ){ | |
if( $field['field_type'] != 'multi_select' || ! $field['taxonomy'] ) | |
return $value; | |
// Locate the legacy value | |
if( ! $value ){ | |
$meta_key = _briand_get_meta_key_by_value( $field['key'], $post_id ); | |
if( $meta_key ){ | |
$meta_key = substr( $meta_key, 1 ); | |
$original_value = get_post_meta( $post_id, $meta_key, true ); | |
if( $original_value && is_string( $original_value ) ){ | |
$value = $original_value; | |
} | |
} | |
} | |
// Either no value or value is already an array | |
if( ! $value || ! is_string( $value ) ) | |
return $value; | |
// convert to an array | |
$classes = explode( ' ', trim( $value ) ); | |
$terms = array(); | |
foreach( $classes as $class ){ | |
$term = get_term_by( 'name', $class, $field['taxonomy'] ); | |
if( $term ){ | |
$terms[] = $term->term_id; | |
} // TODO: add support for missing terms (add term) | |
} | |
if( $terms ) | |
$value = $terms; | |
return $value; | |
} | |
function _briand_get_meta_key_by_value( $meta_value, $post_id = NULL ){ | |
if( ! $post_id ) | |
$post_id = get_the_ID(); | |
global $wpdb; | |
$sql = $wpdb->prepare( "SELECT `meta_key` FROM {$wpdb->postmeta} WHERE `post_id` = %s AND `meta_value` = %s", | |
$post_id, | |
$meta_value | |
); | |
$row = $wpdb->get_row( $sql ); | |
if( ! $row ) | |
return false; | |
return $row->meta_key; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment