在 woocommerce 存档页面和加售/相关产品中显示自定义产品价格

Kry*_*hey 0 php wordpress product custom-fields woocommerce

有没有办法在 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();
}
Run Code Online (Sandbox Code Playgroud)

更新

我找到了一种解决方案,可以在不更改单个产品页面的情况下更改存档页面中的价格:

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 );
Run Code Online (Sandbox Code Playgroud)

问题:实际上,单品页面上的加售和相关产品也应该发生变化。但if (is_product()) return $price_html;它也将它们排除在外。谁帮助解决这个问题将获得赏金。谢谢!

小智 5

if (is_product()) return $price_html;它也将它们排除在外。

使用它代替is_product()对我来说效果很好:

is_single( $product->get_id() )
Run Code Online (Sandbox Code Playgroud)

而且你不应该$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 );
Run Code Online (Sandbox Code Playgroud)