acf woocommerce variations

Solutions on MaxInterview for acf woocommerce variations by the best coders in the world

showing results for - "acf woocommerce variations"
Lukas
16 Jan 2018
1// Render fields at the bottom of variations - does not account for field group order or placement.
2add_action( 'woocommerce_product_after_variable_attributes', function( $loop, $variation_data, $variation ) {
3    global $abcdefgh_i; // Custom global variable to monitor index
4    $abcdefgh_i = $loop;
5    // Add filter to update field name
6    add_filter( 'acf/prepare_field', 'acf_prepare_field_update_field_name' );
7    
8    // Loop through all field groups
9    $acf_field_groups = acf_get_field_groups();
10    foreach( $acf_field_groups as $acf_field_group ) {
11        foreach( $acf_field_group['location'] as $group_locations ) {
12            foreach( $group_locations as $rule ) {
13                // See if field Group has at least one post_type = Variations rule - does not validate other rules
14                if( $rule['param'] == 'post_type' && $rule['operator'] == '==' && $rule['value'] == 'product_variation' ) {
15                    // Render field Group
16                    acf_render_fields( $variation->ID, acf_get_fields( $acf_field_group ) );
17                    break 2;
18                }
19            }
20        }
21    }
22    
23    // Remove filter
24    remove_filter( 'acf/prepare_field', 'acf_prepare_field_update_field_name' );
25}, 10, 3 );
26
27// Filter function to update field names
28function  acf_prepare_field_update_field_name( $field ) {
29    global $abcdefgh_i;
30    $field['name'] = preg_replace( '/^acf\[/', "acf[$abcdefgh_i][", $field['name'] );
31    return $field;
32}
33    
34// Save variation data
35add_action( 'woocommerce_save_product_variation', function( $variation_id, $i = -1 ) {
36    // Update all fields for the current variation
37    if ( ! empty( $_POST['acf'] ) && is_array( $_POST['acf'] ) && array_key_exists( $i, $_POST['acf'] ) && is_array( ( $fields = $_POST['acf'][ $i ] ) ) ) {
38        foreach ( $fields as $key => $val ) {
39            update_field( $key, $val, $variation_id );
40        }
41    }
42}, 10, 2 );