Итак, комиссия 0%, 10%, 20%. в зависимости от цвета, поэтому у нас есть раскрывающийся список с цветом и процентной комиссией от цены товара в корзине.
Я пытаюсь получить значение цвета в поле выбора раскрывающегося списка. При оформлении заказа и в примечаниях к заказу администратора.
На основе связанного исходного кода я преобразовал его из радио в выбор, также с процентом для каждой опции, как изначально.
Проблема в том, что в исходном коде процентное соотношение было установлено следующим образом:
Код: Выделить всё
// no fee
'0' => __( 'Black no fee', 'woocommerce' ),
//15% fee of cart item
'15' => __( 'White 15% fee', 'woocommerce' ) . ' (' . strip_tags( wc_price( 15 * $custom_subtotal / 100 ) ) . ')',
Для нескольких элементов это не сработало, и вместо этого я добавил больше к каждому параметру, как ниже, что заставляет комиссию снова работать, поскольку она должна быть уникальной, поэтому приведенное ниже работает, но только для расчета комиссии, мне также нужно получить значение выбора, поэтому я попробовал;
Код: Выделить всё
// no fee
'0 black' => __( 'Black no fee', 'woocommerce' ),
'0 red' => __( 'Red no fee', 'woocommerce' ),
//15% fee of cart item
'15 White' => __( 'White 15% fee', 'woocommerce' ) . ' (' . strip_tags( wc_price( 15 * $custom_subtotal / 100 ) ) . ')',
'15 blue' => __( 'Blue 15% fee', 'woocommerce' ) . ' (' . strip_tags( wc_price( 15 * $custom_subtotal / 100 ) ) . ')',
Помимо вышеизложенного, что может влиять, основная проблема заключается в том, чтобы перенести вышеизложенное в приведенный ниже $label_text. или, возможно, закомментированный раздел, о котором я не смог разгадать.
полный код, адаптированный из приведенного ниже, и мы делаем несколько хороших вещей, добавили проверку по идентификатору категории, т.е. ограниченную категорией и настраиваемое поле склада, т. е. если он находится на складе.
Переключатели оформления заказа WooCommerce, которые устанавливают процентную плату на основе промежуточной суммы конкретных товаров.
Код: Выделить всё
// Custom function to get related cart items subtotal for specific defined product Ids
function get_related_items_subtotal( $cart ) {
//$targeted_ids = array('8'); // get_meta('_warehouse') == 'no' ) {
$warehouse = true;
// break; // Stop the loop
//}
//if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) {
if ( has_term( $categories, 'pa_brand', $item['product_id'] ) ) {
$category_found = true;
//$custom_subtotal += $item['line_subtotal'] + $item['line_subtotal_tax'];
//$custom_subtotal += $item['line_total'] + $item['line_total_tax'];
$custom_subtotal += $item['line_subtotal'] + $item['line_total_tax'];
}
return $custom_subtotal;
}
}
}
// 1 - Display custom checkout select fields
//add_action( 'woocommerce_review_order_before_payment', 'display_custom_checkout_select' );
add_action( 'woocommerce_after_order_notes', 'display_custom_checkout_select' );
function display_custom_checkout_select() {
$custom_subtotal = get_related_items_subtotal( WC()->cart );
if ( $custom_subtotal > 0 ) {
$value = WC()->session->get( 'colour_surcharge' );
$value = empty( $value ) ? WC()->checkout->get_value( 'colour_surcharge' ) : $value;
$value = empty( $value ) ? '0' : $value;
// echo '
// [h4]' . __("Select Colour option") .'[/h4]';
woocommerce_form_field( 'colour_surcharge', array(
'type' => 'select',
'class' => array( 'form-row-wide', 'update_totals_on_change' ),
'label' => __( 'Colour options, standard or premium', 'woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Select your chosen colour', 'woocommerce' ),
'options' => array(
'0 Black' => __( 'Black - no fee', 'woocommerce' ),
'0 Blue' => __( 'Blue - no fee', 'woocommerce' ),
'10 White' => __( 'White - 10% fee', 'woocommerce' ) . ' (' . strip_tags( wc_price( 10 * $custom_subtotal / 100 ) ) . ')',
'10 Pink' => __( 'Pink - 10% fee', 'woocommerce' ) . ' (' . strip_tags( wc_price( 10 * $custom_subtotal / 100 ) ) . ')',
'20 Grey' => __( 'Grey - 20% surcharge', 'woocommerce' ) . ' (' . strip_tags( wc_price( 20 * $custom_subtotal / 100 ) ) . ')',
),
), $value );
// 2 removed as couldn't figure how to convert
// 2 - Customizing Woocommerce checkout radio form field
/*
add_filter( 'woocommerce_checkout_fields', 'custom_select_field', 20, 4 );
function custom_select_field( $field, $key, $args, $value ) {
if ( ! empty( $args['options'] ) && 'colour_surcharge' === $key && is_checkout() ) {
$field = str_replace( '
Подробнее здесь: [url]https://stackoverflow.com/questions/79076362/how-can-i-get-the-select-field-option-value-from-select-dropdown-as-well-as-cust[/url]