Добавление пользовательских текстовых меток к ценам товара в зависимости от их типа

У меня есть одна маленькая проблема, которую я пока не могу решить.
у меня есть это WooCommerce веб-сайт с переменными продуктами, и в настоящее время цены показаны таким образом:

$ 5.50 за дюжину — $ 100.00 за дюжину

Я использую это правило CSS, которое добавляет «за дюжину» после каждой цены, но не имеет смысла в текущем сценарии.

.price .amount:after {
content: " per dozen";
}

Я хотел бы показать цены на эту переменную продукцию следующим образом:

$ 5,50 за дюжину — 100,00 $ за случай (количество)

Заранее благодарю за любую помощь.

2

Решение

Здесь вы сможете добавлять собственные метки так, как хотите, используя пользовательскую функцию, подключенную к woocommerce_price_html а также woocommerce_variation_price_html фильтры крючки (для простых и переменных продуктов.

Для минимальных / максимальных цен в переменных продуктах нам нужна отдельная функция, подключенная woocommerce_variation_sale_price_html фильтр-крючок.

Обновить: КАК мой код теперь будет обрабатывать также «на дюжину» для отдельных продуктов, Вы должны удалить свое собственное правило CSS .price .amount:after { content: " per dozen";}.

Это позволит избежать повторения «на дюжину» везде.

Но невозможно установить другую метку на реальной цене на основе значений выбранных атрибутов. Для этого единственным способом является использование Javascript / JQuery, так как это живое событие на стороне клиента …

Update2
Вот этот рабочий и проверенный код (см. скриншоты в конце):

add_filter('woocommerce_variation_price_html','prices_custom_labels', 10, 2 );
add_filter('woocommerce_price_html','prices_custom_labels', 10, 2 );
function prices_custom_labels( $price, $product ){

// Custom label name
$per_dozen = ' '. __('per dozen', 'woocommerce' );

// Set HERE your "quantity" attribute slug
$attribute_qty_slug = 'pa_quantity';

$attribute_qty_slug_key = 'attribute_'.$attribute_qty_slug;
$append_label = '';

// 1) Variable products
if ($product->product_type != 'simple' && $product->variation_id ) {

// Getting the attribute "quantity" value
$attribute_qty_is_set = $product->variation_data[$attribute_qty_slug_key];

// if "quantity" not set we display " per dozen"if( ! $attribute_qty_is_set )
$append_label = $per_dozen;// Outputed price + custom label
$price = '<ins class="highlight">'.woocommerce_price( $product->regular_price ).$append_label.'</ins>';
}
// 2) Simple products
else
{
// Here the output price + custom default label
$price = '<ins class="highlight">'.woocommerce_price( $product->regular_price ).$per_dozen.'</ins>';
}
return $price;
}

add_filter('woocommerce_variable_price_html', 'prices_custom_labels_min_max', 20, 2);
function prices_custom_labels_min_max( $price, $product) {

// Custom label name
$per_dozen = ' '. __('per dozen', 'woocommerce' );
$per_case = ' '. __('per case', 'woocommerce' );

// Set HERE your quantity attribute slug
$attribute_qty_slug = 'pa_quantity';// Getting the min and max variations prices
$variation_min_reg_price = $product->get_variation_regular_price('min', true);
$variation_max_reg_price = $product->get_variation_regular_price('max', true);
$variation_reg_price = $product->get_variation_regular_price();if( $variation_min_reg_price == $variation_max_reg_price )
{
$price = '<ins class="highlight">'.woocommerce_price($variation_reg_price) . $per_dozen . '</ins>';
}
else
{
if( !in_array( $attribute_qty_slug, array_keys( $product->get_attributes() ) ) )
{
$price = '<ins class="highlight">' . woocommerce_price($variation_min_reg_price) . $per_dozen . ' - ' . woocommerce_price($variation_max_reg_price) . $per_dozen . '</ins>';
}
else
{
$price = '<ins class="highlight">' . woocommerce_price($variation_min_reg_price) . $per_dozen . ' - ' . woocommerce_price($variation_max_reg_price) . $per_case . '</ins>';
}
}
return $price;
}

Код помещается в файл function.php вашей активной дочерней темы (или темы), а также в любой файл плагина..


Вот реальный скриншот с моего тестового сервера:

введите описание изображения здесь

Этот код протестирован и действительно работает.


Связанные ответы:

5

Другие решения

Этот код решает одну из проблем:

add_filter('woocommerce_variable_price_html',    'prices_custom_labels_min_max', 20, 2);
function prices_custom_labels_min_max( $price, $product) {

// Set HERE your custom labels names
$per_dozen = ' '. __('per dozen', 'woocommerce' );
$per_case = ' '. __('per case', 'woocommerce' );

// Getting the min and max variations prices
$variation_min_reg_price = $product->get_variation_regular_price('min',   true);
$variation_max_reg_price = $product->get_variation_regular_price('max',   true);

if( $variation_min_reg_price == $variation_max_reg_price ){
$price = '<ins   class="highlight">'.woocommerce_price($variation_min_reg_price) . $per_dozen .    '</ins>';
}
else
{
$price = '<ins class="highlight">' .   woocommerce_price($variation_min_reg_price) . $per_dozen . ' - ' .   woocommerce_price($variation_max_reg_price) . $per_case . '</ins>';
}
return $price;
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector