View Categories

如何在WooCommerce变量产品中显示选项名旁边的价格,选择字段?

< 1 min read

将下面的代码加在主题下面的Function.php文件中:


add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name', 10, 1 );
function display_price_in_variation_option_name( $term_name ) {
    global $product;

    if ( is_product() && $product instanceof WC_Product && $product->is_type( 'variable' ) ) {
        foreach ( $product->get_available_variations() as $variation ) {
            foreach ( $variation['attributes'] as $variation_attribute => $term_slug ) {
                $taxonomy = str_replace( 'attribute_', '', $variation_attribute );
                $term     = get_term_by( 'slug', $term_slug, $taxonomy );
                if( is_object($term) && $term->name == $term_name ){
                    $product_price = wc_price( $variation['display_price'] );
                    $product_price = strip_tags( $product_price );
                    return $term_name . ' - (' . $product_price . ')';
                }
            }
        }
    }
    return $term_name;
}