Удалите раскрывающиеся списки вариантов WooCommerce по умолчанию и разрешите отправку параметров продукта.Php

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Удалите раскрывающиеся списки вариантов WooCommerce по умолчанию и разрешите отправку параметров продукта.

Сообщение Anonymous »

Я создал таблицу вариантов продукта, в которой клиенты выбирают цвет, затем отображается таблица размеров, в таблице есть поле количества размеров, и она добавляется в корзину, и все это работает, но по какой-то причине я не могу получить исходные раскрывающиеся списки. быть удален. Я попробовал несколько способов, но по какой-то причине ни один из них не работает.
Вот варианты удаления, которые я пробовал:
// Remove default variation dropdowns
add_action('wp_enqueue_scripts', 'remove_variation_dropdowns', 20);
function remove_variation_dropdowns() {
wp_dequeue_script('wc-add-to-cart-variation');
}

Тогда это:
// Remove the default WooCommerce variation form
remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20);
remove_action('woocommerce_before_single_variation', 'woocommerce_single_variation', 10);
remove_action('woocommerce_before_add_to_cart_form', 'woocommerce_variable_add_to_cart', 30);

Но поле параметров продукта не отправляется при добавлении вариантов в корзину.
См. снимок экрана (красный цвет то, что я хочу удалить, а синий — это то, что нужно отправлять, когда клиент нажимает кнопку «Добавить в корзину» в таблице вариантов):

Изображение

Это мой код (в трёх частях):
1-я часть:
add_action('woocommerce_single_product_summary', 'custom_variation_table', 20);

function custom_variation_table() {
global $product;

if (!$product->is_type('variable')) return; // Only show for variable products

$attributes = $product->get_attributes(); // Get product attributes
$variations = $product->get_available_variations();

// Get Colors if Available
$colors = isset($attributes['pa_color']) ? wc_get_product_terms($product->get_id(), 'pa_color', ['fields' => 'names']) : [];

// Display Color Swatches
if (!empty($colors)) {
echo '';
foreach ($colors as $color) {
$color_slug = strtolower(sanitize_title($color)); // Generate slug
$is_available = check_color_availability($color_slug, $variations);

$class = $is_available ? 'color-swatch' : 'color-swatch disabled';
echo '
';
}
echo '';
}

// Display Variation Table
echo '



Size
Price
Quantity
Add to Cart


';

foreach ($variations as $variation) {
$variation_obj = new WC_Product_Variation($variation['variation_id']);
$variation_price = $variation_obj->get_price_html();
$attributes = $variation_obj->get_attributes();

$color = strtolower($attributes['pa_color'] ?? '');
$size = $attributes['pa_size'] ?? 'N/A';

echo '
' . esc_html(strtoupper($size)) . '
' . $variation_price . '

Add to Cart
';
}

echo '';

// Add Scripts and Styles
enqueue_custom_scripts();
}

function check_color_availability($color_slug, $variations) {
foreach ($variations as $variation) {
$attributes = $variation['attributes'];
if (isset($attributes['attribute_pa_color']) && $attributes['attribute_pa_color'] === $color_slug) {
return true;
}
}
return false;
}

function enqueue_custom_scripts() {
?>

jQuery(document).ready(function ($) {
// Handle swatch click
$('.color-swatch:not(.disabled)').on('click', function () {
var selectedColor = $(this).data('color');
$('.color-swatch').removeClass('selected');
$(this).addClass('selected');

$('.variation-row').each(function () {
$(this).toggle($(this).data('color') === selectedColor);
});

$('.variation-table').fadeIn();
});

// Add to Cart
$('.add-to-cart-btn').on('click', function () {
var button = $(this);
var productId = button.data('product-id');
var variationId = button.data('variation-id');
var quantity = button.closest('tr').find('input[type="number"]').val();

$.ajax({
url: '',
type: 'POST',
data: {
action: 'add_variation_to_cart',
product_id: productId,
variation_id: variationId,
quantity: quantity
},
beforeSend: function () {
button.text('Adding...');
},
success: function (response) {
if (response.success) {
alert(response.data.message);
$(document.body).trigger('wc_fragment_refresh');
} else {
alert(response.data.message);
}
button.text('Add to Cart');
},
error: function () {
alert('Error adding to cart.');
button.text('Add to Cart');
}
});
});
});


/* Styles remain unchanged from the original */
.variation-table { display: none; }
.color-swatch-container { display: flex; gap: 10px; margin-bottom: 20px; }

.color-swatch {
width: 40px; /* Width of the swatch */
height: 40px; /* Height of the swatch */
padding:0 !important;
border-radius: 50px; /* Makes the swatch round */
border: 2px solid #ccc; /* Add a border for better visibility */
cursor: pointer; /* Pointer cursor on hover */
transition: transform 0.2s, border-color 0.2s; /* Smooth hover effects */
}

.color-swatch:hover {
transform: scale(1.1); /* Slightly enlarge on hover */
border-color: #333; /* Change border color on hover */
}

.color-swatch[data-color="white"] {
border: 2px solid #000; /* Add a black border for white swatches */
}
.color-swatch.selected {
border-color: #000; /* Dark border for the selected swatch */
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5); /* Add a subtle shadow */
}
.color-swatch.disabled {
opacity: 0.5; /* Make the swatch appear greyed out */
cursor: not-allowed; /* Change cursor to indicate unavailability */
transform: none; /* Remove hover effects */
border-color: #aaa; /* Light border for disabled swatches */
}
.variation .qty {
width: 3.631em;
text-align: center;
min-height: 35px;
}



Подробнее здесь: https://stackoverflow.com/questions/793 ... ns-to-be-s
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»