Первая цена будет вводиться в админке при создании товара, вторую цену будем рассчитывать по курсу НБРБ, который возьмем с сайта НБРБ. Подобный сервис есть и у Банка России . Для этого скачаем и обработаем xml файл курсов валют. Для того, чтобы исключить ситуацию, когда сайт по каким-либо причинам недоступен, и файл не будет получен, запишем курс доллара в базу с помощью функции add_option(). Затем, уже при выводе, будем брать значения из базы, а не из файла, которого может не существовать - таким образом исключаются возможные ошибки:
function currency_setup() {
$kursi = @simplexml_load_file('http://www.nbrb.by/Services/XmlExRates.aspx'); // получение xml файла курсов всех валют
if ($kursi != FALSE) { // если файл получен
foreach ($kursi->Currency as $Currency) {
if ($Currency->NumCode == '840') // нахождение курса доллара
{
$currency_usd = (double)$Currency->Rate;
if (get_option('currency_usd') != $currency_usd) { // запись значения в базу
update_option('currency_usd', $currency_usd);
} else {
add_option('currency_usd', $currency_usd, '', 'no');
}
}
}
}
}
add_action( 'after_setup_theme', 'currency_setup' );
Однако у этого кода есть недостаток: если файл недоступен, функция simplexml_load_file будет некоторое время пытаться загрузить его, что приведет к медленной загрузке сайта. Чтобы этого избежать, поставим выполнение данной функции по расписанию, тогда она будет срабатывать раз в час, вне зависимости от посещений сайта:
if( ! wp_next_scheduled( 'my_hourly_event' ) )
// добавим новую cron задачу
wp_schedule_event( time(), 'hourly', 'my_hourly_event');
add_action('my_hourly_event', 'do_this_hourly');
function do_this_hourly() {
$kursi = @simplexml_load_file('http://www.nbrb.by/Services/XmlExRates.aspx'); // получение xml файла курсов всех валют
if ($kursi != FALSE) { // если файл получен
foreach ($kursi->Currency as $Currency) {
if ($Currency->NumCode == '840') // нахождение курса доллара
{
$currency_usd = (double)$Currency->Rate;
print_r($kursi);
if (get_option('currency_usd') != $currency_usd) { // запись значения в базу
update_option('currency_usd', $currency_usd);
} else {
add_option('currency_usd', $currency_usd, '', 'no');
}
break;
}
}
}
}
Теперь нужно добавить вторую цену во все товары. В нашем случае это будет выглядеть примерно так: 100 000 руб. (5 $) . Добавим вторую цену для цены простого товара:
add_filter( 'woocommerce_price_html', 'usd_prise', 10, 2 );
function usd_prise( $price, $product ) {
$currency_usd = get_option('currency_usd');
$currency = $product->get_display_price()/$currency_usd;
$price .= ' ('.round($currency).' $)';
return $price;
}
Для цены со скидкой простого товара:
add_filter( 'woocommerce_get_price_html_from_to', 'usd_prise_sale', 10, 3);
function usd_prise_sale( $price, $from, $to) {
$currency_usd = get_option('currency_usd');
$currency = $from/$currency_usd;
$currency_sale = $to/$currency_usd;
$price .= ' ('.round($currency).' $)';
$price = '<del>' . ( ( is_numeric( $from ) ) ? wc_price( $from ) : $from ) .' ('.round($currency).' $)'. '</del> <ins>' . ( ( is_numeric( $to ) ) ? wc_price( $to ) : $to ) .' ('.round($currency_sale).' $)'. '</ins>';
return $price;
}
С вариативным товаром посложнее. Будем использовать старое отображение цены вариативного товара (например От: 1 000 руб.) . Вот код для приведения цены к этому виду:
<?php
// Используем формат цены вариативного товара WC 2.0
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
$currency_usd = get_option('currency_usd');
// Основная цена
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$currency = $prices[0]/$currency_usd;
$price = $prices[0] !== $prices[1] ? sprintf( __( 'От: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Цена со скидкой
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'От: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
$currency_sale = $prices[0]/$currency_usd;
if ( $price !== $saleprice ) {
$price = '<del>' . $saleprice .' ('.round($currency_sale).' $)'. '</del> <ins>' . $price .' ('.round($currency).' $)'.'</ins>';
}
else{
$price .= ' ('.round($currency).' $)';
}
return $price;
}
?>
Теперь добавим отображение цены в валюте:
add_filter( 'woocommerce_variation_price_html', 'usd_prise_var', 10, 2 );
function usd_prise_var( $price, $product ) {
$currency_usd = get_option('currency_usd');
$display_price = $product->get_display_price();
$currency = $display_price /$currency_usd;
$price = wc_price( $display_price ) .' ('.round($currency).' $)'. $product->get_price_suffix();
return $price;
}
И для товаров со скидкой:
add_filter( 'woocommerce_variation_sale_price_html', 'usd_prise_var_sale', 10, 2 );
function usd_prise_var_sale( $price, $product ) {
$currency_usd = get_option('currency_usd');
$display_regular_price = $product->get_display_price( $product->get_regular_price() );
$display_sale_price = $product->get_display_price( $product->get_sale_price() );
$currency = $display_regular_price/$currency_usd;
$currency_sale = $display_sale_price/$currency_usd;
$price= '<del>' . wc_price( $display_regular_price ) .' ('.round($currency).' $)'. '</del> <ins>' . wc_price( $display_sale_price ) .' ('.round($currency_sale).' $)'. '</ins>' . $product->get_price_suffix();
return $price;
}
Данный код вставляем в functions.php вашей темы.
Обновлено: 26.03.2017
Вам помогла эта статья? Оцените!
Здравствуйте, сделал все как написано здесь, но не помогло, что-то не работает.