Chris Pink
Chris Pink

Reputation: 2027

Updating an ACF field after creating a Woocommerce attribute

I have a set of products (courses) that are dependent on a calendar.

The calendar is generated by a post type date which has an ACF field date_start and an associated_product

The logic is; the user creates a post-type Date which adds an attribute term to the associated product's attribute pa_dates.

I have hooked save_post and so far so good, the attribute is written to the product.

I then need to copy the date field to the term created $term_set this section doesn't produce anything. (I need this date to order the terms in my product)

Part of the problem is I have no way of interrogating the variables as this is all happening in a hook that has no way of printing output. (I have tried fwrite but with no result)

// Add terms on Date save.

function add_terms_to_date($post_ID)  {
  if ('date' !== get_post_type() ) {
    return;
  } else {

    $product_id = get_field('associated_product',$post_ID);
    $term_name = get_the_title($post_ID); 
    $taxonomy = 'pa_dates';
    $term_set = wp_set_post_terms( $product_id, $term_name, $taxonomy, true );

    // up to here, works fine.
    // now need to identify that term ($term_set)
    // Then I need to write copy the date field to its ACF field in my Date attribute
    $selector = "term_date_start"; // the ACF field in the term
    $date_start = get_field('date_start', $post_ID); // the date field to be copied
    $value = $date_start; 

    // This next line caused the issue leading to the question so is commented out
    // update_field($selector, $value, $term_set); 
    // and this line is correct
    update_field($selector, $value, $taxonomy."_".$term_set); 
  }
}

add_action('save_post', 'add_terms_to_date');

Upvotes: 0

Views: 117

Answers (1)

Chris Pink
Chris Pink

Reputation: 2027

So, complicated question, simple answer.

The last line should read;

update_field($selector, $value, $taxonomy."_".$term_set); 

to avoid confusion with post IDs (RTFM) ACF has a different system for identifying terms. ($taxonomy comes from the earlier line and is pa_dates)

I have edited the post above, just in case it can provide help to someone.

Upvotes: 0

Related Questions