В Woocommerce я использую плагин WC Fields Factory для сбора информации на странице продукта перед ее добавлением в корзину.Мне нужно получить доступ к данным, которые были введены, чтобы выполнить вычисления в файле функций моей дочерней темы и показать нужную информацию в корзине, но я не смог выяснить, как это сделать.Однако я могу подтвердить, что данные, введенные на странице продукта, добавляются на экраны подтверждения заказа по электронной почте / детали заказа.
На основе " Вес элемента пользовательской корзины в Woocommerce " код ответа, вот моя полная измененная версия кода:
add_filter( 'woocommerce_add_cart_item_data', 'add_weight_custom_cart_item_data', 10, 3 );
function add_weight_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ){
// For product variations handling
$product_id = $variation_id > 0 ? $variation_id : $product_id;
// Get an instance of the product object
$product = wc_get_product( $product_id );
// The default product weight and dimensions
$cart_item_data['weight']['default'] = $product->get_weight() ?: '0'; // Change this to use weight entered on product page (new field)
$cart_item_data['length']['default'] = $product->get_length() ?: '0'; // Change this to use length entered on product page (new field)
$cart_item_data['width']['default'] = $product->get_width() ?: '0'; // Change this to use width entered on product page (new field)
$cart_item_data['height']['default'] = $product->get_height() ?: '0'; // Change this to use height entered on product page (new field)
//___________________ Also add another field 'carton_qty' from the page to use in the below calculations instead of 2
## ====> HERE YOU CAN MAKE YOUR WEIGHT CALCULATIONS <==== ##
$new_weight_value = (($cart_item_data['length']['default'] * $cart_item_data['width']['default'] * $cart_item_data['height']['default']) / 5000);
$old_total_weight = ($cart_item_data['weight']['default'] * 2);
$new_total_weight = ($new_weight_value * 2);
// Set the new calculated weights
$cart_item_data['weight']['new'] = $new_weight_value;
$cart_item_data['weight']['totalold'] = $old_total_weight;
$cart_item_data['weight']['totalnew'] = $new_total_weight;
return $cart_item_data;
}
add_filter( 'woocommerce_get_item_data', 'display_cart_item_weight', 10, 2 );
function display_cart_item_weight( $item_data, $cart_item ) {
if ( isset($cart_item['weight']) ) {
// Display original weight
if ( isset($cart_item['weight']['default']) ) {
$item_data[] = array(
'key' => __('Carton Weight (std)', 'woocommerce'),
'value' => wc_format_weight( $cart_item['weight']['default'] ),
);
}
// Display calculated weight
if ( isset($cart_item['weight']['new']) ) {
$item_data[] = array(
'key' => __( 'Carton Weight (vol)', 'woocommerce' ),
'value' => wc_format_weight( $cart_item['weight']['new'] ),
);
}
// Display calculated original total weight
if ( isset($cart_item['weight']['totalold']) ) {
$item_data[] = array(
'key' => __( 'Line Weight (std)', 'woocommerce' ),
'value' => wc_format_weight( $cart_item['weight']['totalold'] ),
);
}
// Display calculated total weight
if ( isset($cart_item['weight']['totalnew']) ) {
$item_data[] = array(
'key' => __( 'Line Weight (vol)', 'woocommerce' ),
'value' => wc_format_weight( $cart_item['weight']['totalnew'] ),
);
if ($cart_item['weight']['totalold'] < $cart_item['weight']['totalnew']){
echo "<span style='color:#515151;font-size:1.6em;'><b> ⛟</b></span>";
}
}
}
return $item_data;
}
// Set the new weight in cart items
add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_weight', 25, 1 );
function set_custom_cart_item_weight( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach( $cart->get_cart() as $cart_item ){
if ( isset($cart_item['weight']['new']) ) {
$cart_item['data']->set_weight(max ($cart_item['weight']['totalold'], $cart_item['weight']['totalnew']));
}
}
}
Я толькоВ приведенном ниже разделе «Вес и размеры изделия по умолчанию», чтобы использовать данные, предоставленные пользователем, вместо сохраненных сведений о продукте, остальная часть функции вставлена выше для контекста:
// The default product weight and dimensions
$cart_item_data['weight']['default'] = $product->get_weight() ?: '0'; // Change this to use weight entered on product page (new field)
$cart_item_data['length']['default'] = $product->get_length() ?: '0'; // Change this to use length entered on product page (new field)
$cart_item_data['width']['default'] = $product->get_width() ?: '0'; // Change this to use width entered on product page (new field)
$cart_item_data['height']['default'] = $product->get_height() ?: '0'; // Change this to use height entered on product page (new field)
//___________________ Also add another field 'carton_qty' from the page to use in the below calculations instead of 2
Один из примеров,вес отображается в передней части WC Field Factory как имя поля 'carton_weight'.Я пробовал все виды вещей, включая получение мета порядка.Я нашел код в файлах плагинов, который указывает, что я должен использовать $value=["wccpf_carton_weight_1"]
и т. Д., Но ничего из того, что я пробовал, не сработало.
Я использую WC Fields Factory версии 3.0.3 (текущая версия).