有没有办法在WordPress仪表板中启用后端字段,以显示存档页面中每个产品的自定义价格以及加售/相关产品,但是将价格保留在产品摘要中?
示例:产品A的价格为10欧元,但我希望显示“从6欧元/公斤”。
最简单的方法是使用覆盖woocommerce_template_loop_price
的自定义字段,但此代码不起作用,但我不明白为什么。
add_action('woocommerce_template_loop_price', 'shopprice_change', 10, 2);
function shopprice_change ($price, $product) {
global $post, $blog_id;
$post_id = $post->ID;
$price = get_post_meta($post_id, 'shoppricechange', true);
return $price;
wp_reset_query();
}
UPDATE
我找到了一个在不更改单个产品页面的情况下更改存档页面价格的解决方案:
function cw_change_product_html( $price_html, $product ) {
$unit_price = get_post_meta( $product->id, 'shoppricechange', true );
if (is_product()) return $price_html;
if ( ! empty( $unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $unit_price ) . '</span>';
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_html', 10, 2 );
问题:实际上,加售和相关产品也应该在单个产品页面上发生变化。但是if (is_product()) return $price_html;
也把它们排除在外。谁帮助解决这个问题将得到赏金。谢谢!
但是
if (is_product()) return $price_html;
也把它们排除在外。
使用它代替is_product()
对我来说效果很好:
is_single( $product->get_id() )
你不应该直接打电话给$product->id
。相反,使用$product->get_id()
。
这是我使用的完整代码:
function cw_change_product_html( $price_html, $product ) {
if ( is_single( $product->get_id() ) )
return $price_html;
$unit_price = get_post_meta( $product->get_id(), 'shoppricechange', true );
if ( ! empty( $unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $unit_price ) . '</span>';
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_html', 10, 2 );
woocommerce_template_loop_price
也许这个插件可以帮助,Woocommerce Extra Price Fields(来源:function cw_change_product_html( $price_html, $product ) {
$unit_price = get_post_meta( $product->id, 'shoppricechange', true );
$returnedSignleProdctP =false;
$trace = debug_backtrace();
$callstack = (array) $trace;
foreach ($callstack as $key => $value) {
if(isset($value['function']) && $value['function'] == 'woocommerce_output_related_products' ){
if ( ! empty( $unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $unit_price ) . '</span>';
}
}
if(isset($value['function']) && $value['function'] == 'woocommerce_template_single_price' ){
$price_html = $price_html;
}
if(isset($value['function']) && $value['function'] == 'woocommerce_template_loop_price' ){
if ( ! empty( $unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $unit_price ) . '</span>';
}
}
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_html', 10, 2 );
)