在 WooCommerce 中将购物车小计减去购物车总错误问题

Subtracting cart subtotal to cart total error issue In WooCommerce

根据我上一个问题 的答案代码,我现在正尝试将运费作为附加参数添加到 link。

我需要一个 if 语句,确保购物车不是空的。然后我认为最简单的方法就是进行简单的计算,这样就可以得到运费总额(订单总额减去小计)。

问题是;我收到两条通知,上面写着警告:A non-numeric value encountered。警告指的是这一行:

$shipping_total = wc_price($order_total - $order_subtotal);

这是代码:

add_filter( 'wp_nav_menu_header-menu_items', 'minicart_link_with_product_count_subtotal_and_shipping', 10, 2 );
function minicart_link_with_product_count_subtotal_and_shipping( $items, $args ) {

    $order_total = wc_price(WC()->cart->get_total());

    $order_subtotal = wc_price(WC()->cart->get_subtotal());

    $shipping_total = wc_price($order_total - $order_subtotal);

    // cart url
    $link_url = wc_get_cart_url();   

    // icon, product count, subtotal and shipping (based on if statement)
    if (WC()->cart->is_empty()){

        $link_text = sprintf( __( '<i class="shopping-cart"></i> (0)', 'woocommerce' ));

    } else {

        $link_text = sprintf( __( '<i class="shopping-cart"></i> %d - %s (%s)', 'woocommerce' ), WC()->cart->cart_contents_count, wc_price(WC()->cart->get_subtotal()), $shipping_total);

    }

    // link
    $minicart_link = '<a title="View my cart" class="wfminicart" href="' . $link_url . '">' . $link_text . '</a>';

    // return the link as last menu item
    return $items . $minicart_link;
}

您需要从前 2 个变量中删除 wc_price() 格式化函数并将 WC()->cart->get_total() 替换为 WC()->cart->total 以避免此问题。

因此您的代码将是:

add_filter( 'wp_nav_menu_header-menu_items', 'minicart_link_with_product_count_subtotal_and_shipping', 10, 2 );
function minicart_link_with_product_count_subtotal_and_shipping( $items, $args ) {
    $order_total    = WC()->cart->total; // <= Here non formatted total

    $order_subtotal = WC()->cart->get_subtotal();

    $shipping_total = wc_price($order_total - $order_subtotal);

    // cart url
    $link_url = wc_get_cart_url();   

    // icon, product count, subtotal and shipping (based on if statement)
    if (WC()->cart->is_empty()){

        $link_text = sprintf( __( '<i class="shopping-cart"></i> (0)', 'woocommerce' ));

    } else {

        $link_text = sprintf( __( '<i class="shopping-cart"></i> %d - %s (%s)', 'woocommerce' ), WC()->cart->cart_contents_count, wc_price(WC()->cart->get_subtotal()), $shipping_total);

    }

    // link
    $minicart_link = '<a title="View my cart" class="wfminicart" href="' . $link_url . '">' . $link_text . '</a>';

    // return the link as last menu item
    return $items . $minicart_link;
}

它应该可以正常工作。