首页 > 解决方案 > PHP 返回值格式化

问题描述

您能帮我看看如何自定义添加到 wordpress/woocommerce 中的以下代码的输出吗?

目前它显示销售价格和正常价格,我想为它们添加一些自定义,例如:着色(销售价格=红色);文字装饰(销售价格=直通)..

function sr_change_variable_price($price, $product) {
    if ( $product->is_type( 'variable' ) && !is_product() ) 
    {
     return $product->get_variation_regular_price( 'min' ).' '.$product->get_variation_sale_price( 'min' ).' Ft'; // if variable product and non-product page
    } else if ( $product->is_type( 'variable' ) && is_product() )
    {
        return '';  // if variable product and product page
    } else
    {
        return $price;  // other cases
    }
}
add_filter( 'woocommerce_get_price_html', 'sr_change_variable_price', 10, 2 );

非常感谢您的任何帮助,

标签: phpcsswoocommercecolorsformatting

解决方案


在您的函数中,您在第一个条件中连接两个字符串,在第二个条件中返回一个空字符串,并且在 else 语句中返回该自身价格而没有更改。因此,由于您的返回类型是字符串,因此将价格与其他字符串(例如 html 标签)合并是没有问题的。如果此过程对您的 wordpress 的其他过程没有问题,您可以通过在返回中连接它们来使用 html 标签:

function sr_change_variable_price($price, $product){
    $html_tag = '<span style={some styles}>%s</span>';
    if($product->is_type('variable') AND !is_product()){
        $min = $product->get_variation_regular_price('min') . ' ' . $product->get_variation_sale_price('min');
        $min = $min ' Ft';
        return(sprintf($html_tag, $min));
    }elseif($product->is_type('variable') AND is_product()){
        return('');
    }else{
        return(sprintf($html_tag, $price));
    }
}
add_filter('woocommerce_get_price_html', 'sr_change_variable_price', 10, 2);

推荐阅读