首页 > 解决方案 > 如何在不影响相关产品的情况下为单个产品添加自定义价格?

问题描述

我有代码可以用 2 条不同的消息更改所有产品上的自定义消息。请看一下。

add_filter('woocommerce_empty_price_html', 'show_alert_info_if_no_price');
function show_alert_info_if_no_price ($product){
   if (is_product()) {

        global $product;
        $price = $product->get_price();
        if ($price == '') {
        ob_start();
        // return for the product page
        return '<div class="alert-info">Produk ini hanya dapat diproses melakukan pemesanan pembelian (PO). Segera hubungi tim kami. <a href="contactus.php">Kontak kami</a></div>';
    } else {
        // otherwise return short text as kontak kami 
        return 'Contact us';
        }
    }
}

现在我在相关产品上有问题。我需要相关的产品价格将如下所示:

//短文本作为 kontak kami

现在我被卡住了如何在使用 hooked 时添加另一个代码。

$woocommerce_loop['name'] != 'related'). 

任何帮助将不胜感激!

标签: woocommercehook-woocommerce

解决方案


您的代码中有一个错误,因为这个钩子只对空的价格执行。因此,要再次检查挂钩以获取空价格,如果不是,则运行 else 条件是无用的。

要在相关产品的单个产品页面上显示不同的文本,您可以使用global $woocommerce_loop

所以你得到:

function filter_woocommerce_empty_price_html( $html, $product ) {
    global $woocommerce_loop;
    
    // True on a single product page
    if ( is_product() ) {
        $html = '<div class="alert-info">Produk ini hanya dapat diproses melakukan pemesanan pembelian (PO). Segera hubungi tim kami. <a href="contactus.php">Kontak kami</a></div>';
        
        // Related
        if ( $woocommerce_loop['name'] == 'related' ) {
            $html = __( 'Some other text', 'woocommerce' );
        }
    }

    return $html;
}
add_filter( 'woocommerce_empty_price_html', 'filter_woocommerce_empty_price_html', 10, 2 );

推荐阅读