Conditional custom output around products sale price and regular price

谁都会走 提交于 2019-12-02 09:56:02

问题


I'm trying to work on a custom conditional output where when a product loop is found with sales price, it adds a class to the sale price tag. If there's only regular price, it adds this class to regular price tag.

I can't seem to get this to work after looking on & off from different documentations:

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 );
        }
}

I'm using the regular price filter & trying to change the span class="amount" tag to ins span class="amount", however I still get the same output.
Any idea?

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 );
}

回答1:


This hook is a filter with 2 variables ($price and $instance) and you return $price instead of echo $price). You could try to use it this way:

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;
}

This hook is for sale price normally.

Reference: woocommerce_sale_price_html

For regular price, you have woocommerce_price_html filter hook:

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

Reference: woocommerce_price_html




回答2:


You need filter hook here, not action hook, to hook a function or method to a specific filter action. change to

add_filter('woocommerce_sale_price_html','price_custom_class'); 


来源:https://stackoverflow.com/questions/37606772/conditional-custom-output-around-products-sale-price-and-regular-price

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!