WooCommerce: Get custom field from product variations and display it on the “additional information area”

后端 未结 1 854
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 10:50

I\'m trying to add a custom field to product variations, and display the custom field value on products in the \"additional information area\".

I\'m working from \"WooCo

相关标签:
1条回答
  • 2021-01-23 11:36

    At 'value' => get_post_meta( $variation_id, '_custom_field', true ) you make use of the $variation_id while this is not defined.

    So you can make use a foreach loop and $variations->get_children(); instead to add a custom label & value in the "additional information area"

    // 4. Display custom field on the additional information area
    function display_product_attributes( $product_attributes, $variations ) {
        // Get childIDs in an array
        $children_ids = $variations->get_children();
    
        foreach ( $children_ids as $child_id ) {
            $value = get_post_meta( $child_id, 'custom_field', true );
    
            // True
            if ( $value ) {
                // rows
                $product_attributes[ 'custom_field ' . $child_id ] = array(
                    'label' => __('custom', 'woocommerce'),
                    'value' => $value,
                );
            }
        }
    
        return $product_attributes;
    }
    add_filter('woocommerce_display_product_attributes', 'display_product_attributes', 10, 2);
    
    0 讨论(0)
提交回复
热议问题