Пользовательский символ валюты элемента корзины, основанный на категории продукта в Woocommerce 3.3+ - PullRequest
0 голосов
/ 09 октября 2018

Я хочу отобразить пользовательский символ валюты в зависимости от категории продукта.Я взял следующий фрагмент, предложенный по этому вопросу Изменить символ валюты в зависимости от категории продукта в Woocommerce .

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

Это мой код:

add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);

function change_existing_currency_symbol( $currency_symbol, $currency ) {

    global $post, $product, $woocommerce;

    if ( has_term( 'cupones', 'product_cat' ) ) :

        switch( $currency ) {
             case 'EUR': $currency_symbol = 'ptos'; break;
        }
        return $currency_symbol;

    elseif ( has_term( 'cupones', 'product_cat' ) && is_cart() ): 

        switch( $currency ) {
             case 'EUR': $currency_symbol = 'ptos'; break;
        }
        return $currency_symbol;

    elseif ( has_term( 'cupones', 'product_cat' ) && is_checkout() ): 

        switch( $currency ) {
             case 'EUR': $currency_symbol = 'ptos'; break;
        }
        return $currency_symbol;  
    endif;      
}

1 Ответ

0 голосов
/ 10 октября 2018

Обновлено: Для страниц корзины и оформления заказа существует 2 способа: По номеру товара или по всему миру.

1) ПО ПУНКТУ (Наиболее сложный) :

// HERE below your settings
function custom_currency_symbol_settings(){
    return array(
        'curr_symbol' => 'ptos', // <=== HERE define your currency symbol replacement
        'currency'    => 'EUR', // <=== HERE define the targeted currency code
        'category'    => array('cupones'), // <=== HERE define your product category(ies)
        'taxonomy'    => 'product_cat',
    );
}

// On product pages - Custom currency symbol
add_filter( 'woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2 );
function change_existing_currency_symbol( $currency_symbol, $currency ) {
    global $post, $product;

    // Loading your settings
    $data = custom_currency_symbol_settings();

    // Others Woocommerce product pages
    if ( has_term( $data['category'], $data['taxonomy'] ) && $currency == $data['currency'] ) {
        return $data['curr_symbol'];
    }

    return $currency_symbol;
}

// On cart item product price (Cart page) - Custom currency symbol
add_filter( 'woocommerce_cart_product_price', 'change_cart_item_price_currency_symbol', 10, 2 );
function change_cart_item_price_currency_symbol( $product_price_html, $product ) {

    // Loading your settings
    $data = custom_currency_symbol_settings();

    // Get the correct product ID
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only for the defined product category and the defined currency
    if ( ! has_term( $data['category'], $data['taxonomy'], $product_id  ) || get_woocommerce_currency() != $data['currency'] ) {
        return $product_price_html; // Exit
    }

    if ( WC()->cart->display_prices_including_tax() ) {
        $price = wc_get_price_including_tax( $product );
    } else {
        $price = wc_get_price_excluding_tax( $product );
    }

    return wc_price_custom( $price, $data['curr_symbol'] );
}

//  On cart item line subtotal (Cart and Checkout pages) - Custom currency symbol
add_filter( 'woocommerce_cart_product_subtotal', 'change_cart_item_subtotal_currency_symbol', 10, 8 );
function change_cart_item_subtotal_currency_symbol( $product_subtotal, $product, $quantity, $cart ) {

    // Loading your settings
    $data = custom_currency_symbol_settings();

    // Get the correct product ID
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only for the defined product category and the defined currency
    if ( ! has_term( $data['category'], $data['taxonomy'], $product_id  ) || get_woocommerce_currency() != $data['currency'] ) {
        return $product_price_html; // Exit
    }

    if ( $product->is_taxable() ) {

        if ( $cart->display_prices_including_tax() ) {
            $row_price        = wc_get_price_including_tax( $product, array( 'qty' => $quantity ) );
            $product_subtotal = wc_price_custom( $row_price, $data['curr_symbol'] );

            if ( ! wc_prices_include_tax() && $cart->get_subtotal_tax() > 0 ) {
                $product_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
            }
        } else {
            $row_price        = wc_get_price_excluding_tax( $product, array( 'qty' => $quantity ) );
            $product_subtotal = wc_price_custom( $row_price, $data['curr_symbol'] );

            if ( wc_prices_include_tax() && $cart->get_subtotal_tax() > 0 ) {
                $product_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
            }
        }
    } else {
        $row_price        = $product->get_price() * $quantity;
        $product_subtotal = wc_price_custom( $row_price, $data['curr_symbol'] );
    }
    return $product_subtotal;
}

// Custom formatting price function replacement
function wc_price_custom( $price, $curr_symbol, $args = array() ){
    extract( apply_filters( 'wc_price_args', wp_parse_args( $args, array(
        'ex_tax_label'       => false,
        'currency'           => '',
        'decimal_separator'  => wc_get_price_decimal_separator(),
        'thousand_separator' => wc_get_price_thousand_separator(),
        'decimals'           => wc_get_price_decimals(),
        'price_format'       => get_woocommerce_price_format(),
    ) ) ) );

    $unformatted_price = $price;
    $negative          = $price < 0;
    $price             = apply_filters( 'raw_woocommerce_price', floatval( $negative ? $price * -1 : $price ) );
    $price             = apply_filters( 'formatted_woocommerce_price', number_format( $price, $decimals, $decimal_separator, $thousand_separator ), $price, $decimals, $decimal_separator, $thousand_separator );

    if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {
        $price = wc_trim_zeros( $price );
    }

    $formatted_price = ( $negative ? '-' : '' ) .
        sprintf( $price_format, '<span class="woocommerce-Price-currencySymbol">' . $curr_symbol . '</span>', $price );
    $return          = '<span class="woocommerce-Price-amount amount">' . $formatted_price . '</span>';

    if ( $ex_tax_label && wc_tax_enabled() ) {
        $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
    }
    return apply_filters( 'wc_price', $return, $price, $args, $unformatted_price );
}

2) GLOBALLY (намного проще) :

Следующий код, основанный на настройках вашего кода, будетизменить символ валюты глобально на корзине и на страницах оформления заказа, когда категория продукта «купоны» найдена в любом элементе корзины:

add_filter( 'woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2 );
function change_existing_currency_symbol( $currency_symbol, $currency ) {
    global $post, $product;

    $custom_sym = 'ptos'; // <=== HERE define your currency symbol replacement
    $custom_cur = 'EUR'; // <=== HERE define the targeted currency code
    $category   = array('cupones'); // <=== HERE define your product category(ies)
    $taxonomy   = 'product_cat';

    // Cart and checkout
    if( ( is_cart() || is_checkout() ) && $currency == $custom_cur ){
        foreach( WC()->cart->get_cart() as $cart_item ){
            if ( has_term( $category, $taxonomy, $cart_item['product_id'] ) ){
                return $custom_sym; // Found! ==> we return the custom currency symbol
            }
        }
    }

    // Others Woocommerce product pages
    if ( has_term( $category, $taxonomy ) && $currency == $custom_cur ) {
        return $custom_sym;
    }

    return $currency_symbol;
}

Код входит в файл function.php вашей активной дочерней темы(или активная тема). Проверено и работает.

...