'Can I use a WooCommerce function without any WooCommerce page?
I've WooCommerce installed on my WordPress site. After this, I've created a custom page template that has nothing to do with WooCommerce. Within this template, I want to use the WooCommerce wc_price()
function but it doesn't work. This is what I've tried:
global $woocommerce;
$woocommerce->wc_price(12);
--
WC()->wc_price(12);
But both of this don't works. So how can I use this function within my custom template (if possible)?
Solution 1:[1]
You can simply use the function without WC object. Below is the definition of that function. So you can simply use like wc_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 );
}
Solution 2:[2]
If you wanna get product price ,you can use this code:
global $product;
$product->get_price());
Solution 3:[3]
require_once( ABSPATH . 'wp-load.php' );
Just write this in any of your template and then you can access woocommerce content like products, orders. I have tried it and well worked..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mujuonly |
Solution 2 | Abdurahmon Odinaev |
Solution 3 | Hritik Pandey |