首页 > 解决方案 > 我可以在没有任何 WooCommerce 页面的情况下使用 WooCommerce 功能吗?

问题描述

我已经在我的 WordPress 网站上安装了 WooCommerce。在此之后,我创建了一个与 WooCommerce 无关的自定义页面模板。在此模板中,我想使用 WooCommercewc_price()功能,但它不起作用。这是我尝试过的:

global $woocommerce;
$woocommerce->wc_price(12);
--
WC()->wc_price(12);

但这两种方法都不起作用。那么如何在我的自定义模板中使用此功能(如果可能)?

标签: phpwordpresswoocommerce

解决方案


您可以简单地使用没有 WC 对象的函数。下面是该函数的定义。所以你可以简单地使用 likewc_price(12)

function wc_price( $price, $args = array() ) {
    $args = 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, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'] ), $price, $args['decimals'], $args['decimal_separator'], $args['thousand_separator'] );

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

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

    if ( $args['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 );
}

推荐阅读