Add Advanced Custom Fields to WooCommerce Product Variation

后端 未结 3 1961
鱼传尺愫
鱼传尺愫 2021-01-25 03:18

I am using plugins called Advanced Custom Fields (ACF) and WooCommerce. I want to create a text and image field for WooCommerce product variation. I created fields in ACF and as

3条回答
  •  日久生厌
    2021-01-25 03:41

    I faced this problem myself and given how frequently WooCommerce changes I was hesitant to shim some extra fields in with code. I did figure out a minimal code workaround which may or may not fit your needs. Essentially it's "proxying" the variation's custom fields in a regular post and accessing those fields by putting that post ID in the product variation's SKU field.

    I started by setting up a post category "custom-fields" - which I hide via a redirect to the similarly named product. I set up my custom fields for the post category: custom-fields and then I added a post e.g. "widget x red" and I input the custom fields for the red variation. Once the post saved I added the post ID to the product variation SKU field. Customizing the CSS I hid the SKU field and editing the child theme woocommerce/single-product.php I added a little PHP to retrieve the custom fields.

    $product = wc_get_product($post->ID);
    $pv = new WC_Product_Variable($product->get_id());
    $variations = $pv->get_available_variations();  
    $custom_fields=[];
    if(!empty($variations)){
        foreach($variations as $variation){
            $vid = $variation['variation_id'];
            $sku = $variation['sku'];
            if($vid && $sku){
                $fields = get_fields($sku);
                if($fields){
                    $custom_fields[$vid] = $fields;
                }
            }
        }
    }
    

    After which I had the custom fields indexed by variation ID

提交回复
热议问题