Support

Account

Home Forums Add-ons Repeater Field update_sub_field with taxonomy field

Helping

update_sub_field with taxonomy field

  • I have a repeater fields where one field is a select field (variety). Users have submitted data to that field, but I now want to change that field to a taxonomy field. So I created a custom taxonomy with the same term names as the select field in the existing repeater. Then I added a taxonomy field to the repeater and set it to this custom taxonomy (tax_variety). Now, I want to loop through my posts and for each post, loop through the repeater, then take the value of variety, see if it matches a term name in tax_variety and, if so, set tax_variety to that term.

    Here is my code (from inside the loop):

    if ( $items->have_posts() ) {
      $tax_var = get_terms('varieties_grown', 'hide_empty=0');
      $tax_var_array = array();
      foreach ( $tax_var as $tax ) {
        $tax_var_array[] = array('term_id' => $tax->term_id, 'name' => $tax->name );
      }
      while( $items->have_posts() ) {
        $items->the_post();
        $post_id = get_the_ID();
        $varieties = get_field('field_57d8b8c860d41');
        if ( $varieties ) {
          for ($x = 0; $x < count($varieties); $x++ ) {
            $v = $varieties[$x];
            $key =  array_search( $v['variety'], array_column( $tax_var_array, 'name' ) );
            if ( $key ) update_sub_field($v['tax_variety'], $tax_var[$key]);
        }
      }
    }

    In this case, I used the tax term object with update_sub_field, I also tried just the ID, but neither seems to work. I echoed all the values and they are correct, so it’s coming down to the update statement that seems to be failing.

    BTW, the $tax_var_array that I create was basically just to make it easier for me to do the array_search. Probably could have done it with the term objects, but my head is hurting too much to think about it.

  • Never mind! I fixed it by using the full field keys instead of slugs. Here’s the working code:

    if ( $items->have_posts() ) {
      $tax_var = get_terms('varieties_grown', 'hide_empty=0');
      $tax_var_array = array();
      foreach ( $tax_var as $tax ) {
        $tax_var_array[] = array('term_id' => $tax->term_id, 'name' => $tax->name );
      }
      while( $items->have_posts() ) {
        $items->the_post();
        $post_id = get_the_ID();
        if( have_rows('field_57d8b8c860d41')):
          while ( have_rows( 'field_57d8b8c860d41' ) ) : the_row();
            $variety = get_sub_field( 'field_57d8b8dc60d42' );
            $key = array_search( $variety, array_column( $tax_var_array, 'name' ) );
            if ( $key ) {
              $term_id = $tax_var_array[$key]['term_id'];
              update_sub_field('field_5894f9fbbad27', $term_id );
            }
    
          endwhile;
        endif;
      }
    }
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘update_sub_field with taxonomy field’ is closed to new replies.