【问题标题】:Conditional custom output around products sale price and regular price围绕产品销售价格和正常价格的条件自定义输出
【发布时间】:2016-06-03 05:45:53
【问题描述】:

我正在尝试处理自定义条件输出,当找到带有销售价格的产品循环时,它会向销售价格标签添加一个类。如果只有正常价格,则将此类添加到正常价格标签中。

在查看不同的文档后,我似乎无法让它工作:

add_filter( 'woocommerce_get_price_html', 'custom_price_html', 100, 2 );
function custom_price_html( $price, $product ){
    ob_start();
        global $product; 
        if (isset($product->sale_price)) {
            return str_replace( '</del>', '<span class="amount">text</span></del>', $price );
            return str_replace( '</ins>', '<span class="highlight amount">highlight here</span></del>', $price );
        }
        else {
            return str_replace( '</ins>', '<span class="highlight amount">highlight here</span>text</del>', $price );
        }
}

我正在使用常规价格过滤器并尝试将 span class="amount" 标签更改为 ins span class="amount",但我仍然得到相同的输出。
有什么想法吗?

add_filter( 'woocommerce_price_html', 'price_custom_class', 10, 2 );
function price_custom_class( $price, $product ){ 
    return str_replace( '<span class="amount"></span>', '<ins><span class="amount">'.woocommerce_price( $product->regular_price    ).'</span></ins>', $price );
}

【问题讨论】:

    标签: php wordpress woocommerce product price


    【解决方案1】:

    这个钩子是一个带有 2 个变量($price$instance)的过滤器,而你是 return $price 而不是 echo $price)。你可以尝试这样使用它:

    add_filter('woocommerce_sale_price_html','price_custom_class', 10, 2 ); 
    function price_custom_class( $price, $product ){ 
        if (isset($product->sale_price)) {
            $price = '<del class="strike">'.woocommerce_price( $product->regular_price ).'</del> 
            <ins class="highlight">'.woocommerce_price( $product->sale_price ).'</ins>';
        }
        else
        {
            $price = '<ins class="highlight">'.woocommerce_price( $product->regular_price ).'</ins>';
        }
        return $price;
    }
    

    这个钩子是正常售价。

    参考:woocommerce_sale_price_html

    对于正常价格,你有woocommerce_price_html过滤钩:

    add_filter( 'woocommerce_price_html', 'price_custom_class', 10, 2 );
    function price_custom_class( $price, $product ){ 
        // your code
        return $price;
    }
    

    参考:woocommerce_price_html

    【讨论】:

      【解决方案2】:

      您需要在这里使用过滤器挂钩,而不是操作挂钩,以将函数或方法挂钩到特定的过滤器操作。 改为

      add_filter('woocommerce_sale_price_html','price_custom_class'); 
      

      【讨论】:

      • 是的,我发现过滤器钩子在我通过它 5 分钟后将是正确的方式。看起来我将同时替换 sale_price 和 regular_price,get_price_html 会更好吗?
      • 是的,当您使用 get_price_html 函数调用时它会显示替换值
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多