Gao*_*aou 1 php wordpress product woocommerce price
IN WooCommerce我使用此的代码胎面用短代码以显示产品的价格从定义的产品ID.但它并没有真正做到我想要的.这是代码:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$number = number_format($_product->get_price(), 2, '.', ',');
$html = "$" . $number;
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Run Code Online (Sandbox Code Playgroud)
我对PHP编码知之甚少.但我已经看到有这个其他线程来显示产品价格:
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Run Code Online (Sandbox Code Playgroud)
我试图将这些代码混合到大代码中,并替换get_price()
......它可以工作,但我想要的是显示价格是这样的:
所以正常价格划掉了,旁边的促销价就像在这个截图中一样.如果没有促销价,则仅显示正常价格.
我还有一些其他问题:
我需要显示价格€
,而不是$
,因此我已使用以下代码将货币符号从$
(美元)替换为€
(欧元):$html = "€" . $number;
我需要在价格后面显示货币符号,例如:( 37 €
之间有空格),而不是$37
.
如何以干净的正常方式使其工作?
更新 (考虑您的价格是否带税或显示)
使用Woocommerce wc_price()
,您可以在代码中使用格式化价格函数.你需要得到销售价格 ......
要在有售价或没有售价的情况下使用此代码(注释):
function custom_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'product_price' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
// Get an instance of the WC_Product object
$product = wc_get_product( intval( $atts['id'] ) );
// Get the product prices
$price = wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) ); // Get the active price
$regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ); // Get the regular price
$sale_price = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ); // Get the sale price
// Your price CSS styles
$style1 = 'style="font-size:40px;color:#e79a99;font-weight:bold;"';
$style2 = 'style="font-size:25px;color:#e79a99"';
// Formatting price settings (for the wc_price() function)
$args = array(
'ex_tax_label' => false,
'currency' => 'EUR',
'decimal_separator' => '.',
'thousand_separator' => ' ',
'decimals' => 2,
'price_format' => '%2$s %1$s',
);
// Formatting html output
if( ! empty( $sale_price ) && $sale_price != 0 && $sale_price < $regular_price )
$html = "<del $style2>" . wc_price( $regular_price, $args ) . "</del> <ins $style1>" . wc_price( $sale_price, $args ) . "</ins>"; // Sale price is set
else
$html = "<ins $style1>" . wc_price( $price, $args ) . "</ins>"; // No sale price set
}
return $html;
}
add_shortcode( 'product_price', 'custom_price_shortcode_callback' );
Run Code Online (Sandbox Code Playgroud)
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.
用法 (例如产品ID 37
):
[product_price id="37"]
Run Code Online (Sandbox Code Playgroud)
此代码经过测试和运行.你会得到这个:
归档时间: |
|
查看次数: |
6680 次 |
最近记录: |