我通过 xml feed 上传运行我的 woocommerce 产品更新。然而,当产品不打折时,销售价格将设置为 0 并且有些为空白。
我想要一种情况,当产品的销售价格为 0 时,它应该只显示正常价格。我确实让它与这段代码一起工作
add_action ('woocommerce_before_shop_loop_item', 'check_sale_price', 40 );
add_action('woocommerce_before_single_product', 'check_sale_price', 40 );
function check_sale_price() {
global $product;
if ( $product->sale_price == '0' ) {
$price = $product->regular_price;
$product->sale_price = $price;
$product->price = $price;
global $wpdb;
$wpdb->get_results( 'UPDATE wp_postmeta SET meta_value='.$price.' WHERE meta_key="_sale_price" AND post_id='.$product->id, OBJECT );
$wpdb->get_results( 'UPDATE wp_postmeta SET meta_value='.$price.' WHERE meta_key="_price" AND post_id='.$product->id, OBJECT );
}
}
但是 woocommerce 只会在下面显示此内容,而不仅仅是常规价格。
您的代码自 Woocommerce 3 以来已过时并且有点繁重,请尝试以下操作:
add_action('woocommerce_before_shop_loop_item', 'check_sale_price', 1 );
add_action('woocommerce_before_single_product', 'check_sale_price', 1 );
function check_sale_price() {
global $product;
if( $product->get_sale_price() == '0' ) {
$product->set_sale_price(''); // Empty sale price
$product->set_price( $product->get_regular_price() ); // Set regular price back
$product->save(); // Save and update caches
}
}
// Change the displayed matching prices (to be sure)
add_filter('woocommerce_get_price_html', 'custom_price_html', 10, 2 );
function custom_price_html( $price, $product ) {
if ( $product->is_on_sale() && $product->get_sale_price() == '0' ) {
$price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) ) . $product->get_price_suffix();
}
return $price;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。应该可以。