簡體   English   中英

如何在 WooCommerce 中獲得所有可用的稅率?

[英]How can I get all available tax rates in WooCommerce?

我目前正在構建一個自定義表單。 在此表單中,我想顯示結帳時已存在的國家/地區選擇。

這是我的稅務設置列表:

在此處輸入圖片說明

這是我的代碼:

<select class="country-select">
    <?php
    foreach ( WC_Tax::get_rates() as $rate ) {
        echo '<option value="' . $rate->tax_rate . '">' . $rate->country . '</option>';
    }
    ?>
</select>

我期待以下選項:

<option value="19">Deutschland</option>
<option value="20">Österreich</option>

問題是我沒有從get_rates()函數中得到任何結果。 我發現沒有任何函數可以返回正確的費率。 你知道我怎么能做到這一點嗎?

TL; 博士

$all_tax_rates = [];
$tax_classes = WC_Tax::get_tax_classes(); // Retrieve all tax classes.
if ( !in_array( '', $tax_classes ) ) { // Make sure "Standard rate" (empty class name) is present.
    array_unshift( $tax_classes, '' );
}
foreach ( $tax_classes as $tax_class ) { // For each tax class, get all rates.
    $taxes = WC_Tax::get_rates_for_tax_class( $tax_class );
    $all_tax_rates = array_merge( $all_tax_rates, $taxes );
}

解釋:

據我所知,您只能獲得給定特定tax_class的所有稅率的列表,該列表用於按tax_rate_class列過濾woocommerce_tax_rates表(好吧,我們總是可以直接查詢數據庫,但我假設您想使用 WooCommerce 提供的功能解決問題)。 此外,“標准費率”沒有tax_class ,即。 tax_rate_class列是一個空字符串。

因此,如果您想獲取每個類別的所有稅率,則需要使用WC_Tax::get_rates_for_tax_class( $tax_class ) 但是如果你真的想要所有稅率而不管等級,你需要先得到所有稅種,然后得到每個等級的所有稅率。

如果您配置了稅率,則它們可能不涵蓋您登錄的任何用戶。

嘗試將$tax_class$customer參數提供給您的WC_Tax::get_rates方法! 特別是您示例中的德國和/或 Österreich 稅率適用的客戶和稅種!

此處查看實際的函數定義:

<?php

// class-wc-tax.php

class WC_Tax {
// ...
    /**
     * Get's an array of matching rates for a tax class.
     *
     * @param string $tax_class Tax class to get rates for.
     * @param object $customer Override the customer object to get their location.
     * @return  array
     */
    public static function get_rates( $tax_class = '', $customer = null ) {
        $tax_class         = sanitize_title( $tax_class );
        $location          = self::get_tax_location( $tax_class, $customer );
        $matched_tax_rates = array();

        if ( count( $location ) === 4 ) {
            list( $country, $state, $postcode, $city ) = $location;

            $matched_tax_rates = self::find_rates(
                array(
                    'country'   => $country,
                    'state'     => $state,
                    'postcode'  => $postcode,
                    'city'      => $city,
                    'tax_class' => $tax_class,
                )
            );
        }

        return apply_filters( 'woocommerce_matched_rates', $matched_tax_rates, $tax_class );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM