Home Forums General Issues Convert an ACF field to taxonomy Reply To: Convert an ACF field to taxonomy

  • So I was searching for how to do this and this support doc was the first result on Google. I have a case where we set-up custom fields for the admins to sort in the dashboard but now want to convert the fields to a taxonomy in order to display as categories on the front end. I ended up working with ChatGPT for an hour starting with this framework and have achieved this result–which surprisingly seems to work as expected. But I wanted to post it here not only because it is a potential solution for other users seeking this out, but also because I am a systems integrator more-so than a formal developer and I am wondering what more expert folks would make of this work? Is it sound?

    function convert_field_to_terms() {
        if (!is_admin()) {
            return; // Only run on the frontend
        $args = array(
            'post_type' => 'portfolio',
            'posts_per_page' => -1,
        $query = new WP_Query($args);
        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $acf_value = get_field('admin_theme');
                if ($acf_value) {
                    $term_ids = array(); // Array to store term IDs
                    if (!is_array($acf_value)) {
                        $acf_value = array($acf_value); // Convert to array if it's not already
                    foreach ($acf_value as $value) {
                        $term = get_term_by('name', $value, 'public-theme');
                        if (!$term) {
                            $term_args = array(
                                'slug' => sanitize_title($value),
                            $term = wp_insert_term($value, 'public-theme', $term_args);
                            if (!is_wp_error($term) && isset($term['term_id'])) {
                                $term_ids[] = $term['term_id']; // Add the term ID to the array
                        } elseif (!is_wp_error($term)) {
                            $term_ids[] = $term->term_id; // Add the term ID to the array
                    wp_set_object_terms(get_the_ID(), $term_ids, 'public-theme', false);
                update_post_meta(get_the_ID(), 'state_update_complete', '1');
    add_action('init', 'convert_field_to_terms');